在Python中处理JSON
{"required_items":[
{
"filename":"abcd",
"no":"3"
},
{
"filename":"abc",
"no":"2"
}
]}
我在Python中无法获取JSON格式的代码 - 我想通过循环插入文件名和编号。
list_of_other_ids={}
for i in xxxx:
entry={}
entry['filename'] = "XXXX"
entry['no'] =XX
list_of_other_ids.append(entry)
我这样做...但失败了。
1 个回答
5
# data.txt
{"required_items":[
{
"filename":"abcd",
"no":"3"
},
{
"filename":"abc",
"no":"2"
}
]}
# parser.py
import json
data = json.load(open('data.txt'))
for file in data:
print file['filename']
# This will output:
# abcd
# abc
如果你想添加新的项目:
data.append({ 'filename': 'foo',
'nr': 1 })
json.dump(data, open('data.txt', 'w'))