簡體   English   中英

在python中將列表轉換為json

[英]Converting a list to json in python

這是代碼,我有一個列表,我想使用動態鍵將其轉換為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。

 data = []
 for entry in lst:
    data.append({'key'+str(lst.index(entry)):entry})

 json.dump(data, outfile)

枚舉列表(你不應該調用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"}'

作為我最初在評論中發布的最小更改:

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.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)

盡管那樣您會開始失去可讀性,所以我不建議您走那么遠。

這是您需要做的:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM