这是代码,我有一个列表,我想用动态密钥转换为JSON。
>>> print (list) #list
['a', 'b', 'c', 'd']
>>> outfile = open('c:\\users\\fawads\desktop\csd\\Test44.json','w')#writing data to file
>>> for entry in list:
... data={'key'+str(i):entry}
... i+=1
... json.dump(data,outfile)
...
>>> outfile.close()
结果如下:
{"key0": "a"}{"key1": "b"}{"key2": "c"}{"key3": "d"}
哪个是无效的json。
答案 0 :(得分:1)
data = []
for entry in lst:
data.append({'key'+str(lst.index(entry)):entry})
json.dump(data, outfile)
答案 1 :(得分:1)
枚举您的列表(顺便说一句,您不应该调用list
,这将隐藏内置列表):
>>> import json
>>> lst = ['a', 'b', 'c', 'd']
>>> jso = {'key{}'.format(k):v for k, v in enumerate(lst)}
>>> json.dumps(jso)
'{"key3": "d", "key2": "c", "key1": "b", "key0": "a"}'
答案 2 :(得分:1)
作为我最初在评论中发布的最小变化:
outfile = open('c:\\users\\fawads\desktop\csd\\Test44.json','w')#writing data to file
all_data = [] #keep a list of all the entries
i = 0
for entry in list:
data={'key'+str(i):entry}
i+=1
all_data.append(data) #add the data to the list
json.dump(all_data,outfile) #write the list to the file
outfile.close()
多次在同一个文件上调用json.dump
很少有用,因为它创建了需要分离的多个json数据段才能被解析,只需要调用它就更有意义完成构建数据后。
我还建议您使用enumerate
来处理i
变量以及使用with
语句来处理文件IO:
all_data = [] #keep a list of all the entries
for i,entry in enumerate(list):
data={'key'+str(i):entry}
all_data.append(data)
with open('c:\\users\\fawads\desktop\csd\\Test44.json','w') as outfile:
json.dump(all_data,outfile)
#file is automatically closed at the end of the with block (even if there is an e
循环可以通过列表理解进一步缩短:
all_data = [{'key'+str(i):entry}
for i,entry in enumerate(list)]
哪个(如果你真的想要)可以直接放入json.dump
:
with open('c:\\users\\fawads\desktop\csd\\Test44.json','w') as outfile:
json.dump([{'key'+str(i):entry}
for i,entry in enumerate(list)],
outfile)
尽管那时你开始失去可读性,所以我不建议你去那么远。
答案 3 :(得分:0)
以下是您需要做的事情:
mydict = {}
i = 0
for entry in list:
dict_key = "key" + str(i)
mydict[dict_key] = entry
i = i + 1
json.dump(mydict, outfile)
目前,您正在循环的每次迭代中创建一个新的dict条目,因此结果不是有效的json。