[英]Complex JSON object from CSV String in Python
I want the below JSON output after parsing csv string in Python to feed API:在解析 Python 中的 csv 字符串后,我想要下面的 JSON output 来馈送 API:
{
"_records":[
{
"_fields":{
"Account":"DSP2",
"Code":"11"
}
},
{
"_fields":{
"Account":"DSP1",
"Code":"11"
}
}
]
}
Since I am new to python after some research I was able to write the below code, which is working, but I am getting some additional junk characters in the final output.由于我是 python 的新手,经过一些研究后我能够编写下面的代码,它正在运行,但我在最终的 output 中得到了一些额外的垃圾字符。
Output: Output:
{'records': [{'{"fields": {"Account": "T671", "Code": "A7710"}}'},
enter code here
"T672", "Code": "A7799"}}'}]}
can someone help on how to get rid of extra {' and '}?有人可以帮助摆脱多余的 {' 和 '} 吗?
Code -代码 -
data = {'records': []}
data1 = {}
line_var = input_var_1.splitlines()
for line in line_var:
records = line.split(',')
data1.update({'fields': {'Account': records[0].strip(),'Code': records[1].strip()}})
data2 = json.dumps(data1)
data["records"].append({data2})
the additional {'
is there because you dump the inner dictionary to a string and insert it into a set which you then put in the list.附加的{'
在那里是因为您将内部字典转储为一个字符串并将其插入到一个集合中,然后将其放入列表中。
Leave the data2 = json.dumps(data1)
out and just insert data1
in your data["records"]
.保留data2 = json.dumps(data1)
并在您的data["records"]
中插入data1
。 You'll get a proper list of dictionaries that you can use further你会得到一个合适的字典列表,你可以进一步使用
Only dump the dictionary if you need it's text-representation for writing it to a file etc.只有在需要将字典写入文件等的文本表示时才转储字典。
You also don't need to initialize the data1
dictionary, just assign a new one in every loop and write it to the list.您也不需要初始化data1
字典,只需在每个循环中分配一个新字典并将其写入列表即可。 It will overwrite the reference by default它会默认覆盖引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.