我需要将函数getvalues返回的字典添加到“data.update”中 我可以添加为单独的json。但无法在字段键中添加它。请检查输出和所需的输出。
这是我写的代码:
import json
import csv
import glob
import os
csvfile = open('file.csv', 'r')
name = (os.path.splitext('file.csv')[0])
exampleReader = csv.reader(csvfile)
exampleData = list(exampleReader)
def getvalues():
for row in exampleData[:1]:
lis = {}
for r in row:
lis.update({r:r})
return lis
data = {}
data.update({
"pattern": name+'.csv',
"source_args": {
"encoding": "UTF-16"
},
"parser_args": {
"type": "csv",
"delimiter": ","
},
"outputs": [
{
"name": name,
"fields": {
}
}
]
})
result =json.dumps(data)
result1 =json.dumps(getvalues())
file = open("data.json","w")
file.write(result)
file.write(result1)
以下是实际输出和所需输出:
#Output : {"pattern": "file.csv",
"source_args":
{
"encoding": "UTF-16"
},
"parser_args": {
"type": "csv",
"delimiter": ","
}, "outputs":
[
{
"name": "file",
"fields": {}
}
]}
{
"facility_id": "facility_id",
"facility_type": "facility_type",
"facility_name": "facility_name",
"facility_branch": "facility_branch",
}
#Desired Output : {"pattern": "file.csv",
"source_args":
{
"encoding": "UTF-16"
},
"parser_args": {
"type": "csv",
"delimiter": ","
}, "outputs":
[
{
"name": "file",
"fields": {
"facility_id": "facility_id",
"facility_type": "facility_type",
"facility_name": "facility_name",
"facility_branch": "facility_branch",
}
}
]}
拜托,让我知道如何实现这一目标。
更新:错误
如果我以下列方式直接添加功能。 fields {getvalues()} 。我收到以下错误。
Traceback (most recent call last):
File "chej.py", line 50, in <module>
getvalues()
TypeError: unhashable type: 'dict'
答案 0 :(得分:0)
你可以试试这个:
"outputs": [
{
"name": name,
"fields": getvalues()
}