我目前有两个需要使用python组合的json文件。基本上我想使用python将文件1中的choices数组替换为文件2中的数组。我该怎么做呢? 文件1是:
{
"choice_list": {
"name": "Boston Street Names",
"choices":[ {"value": "127906", "label": "DAVIS STREET"},
{"value": "129909", "label": "NORTH QUINCY STREET" },
{ "value": "134194", "label": "ADAMS STREET" }]
}
}
文件2是:
[{"value": "134484", "label": "PRISCILLA ALDEN ROAD"},
{"value": "134487", "label": "VAN BUREN DRIVE"}]
答案 0 :(得分:2)
使用本机python JSON库:
import json
json1 = '{\
"choice_list": {\
"name": "Boston Street Names",\
"choices":[ {"value": "127906", "label": "DAVIS STREET"},\
{"value": "129909", "label": "NORTH QUINCY STREET" },\
{ "value": "134194", "label": "ADAMS STREET" }]\
} \
}'
json2 = '[{"value": "134484", "label": "PRISCILLA ALDEN ROAD"},\
{"value": "134487", "label": "VAN BUREN DRIVE"}]'
res = json.loads(json1)
res['choice_list']['choices'] = json.loads(json2)
print json.dumps(res)
结果:
{"choice_list":
{"name": "Boston Street Names",
"choices":
[{"value": "134484","label": "PRISCILLA ALDEN ROAD"},
{"value": "134487", "label": "VAN BUREN DRIVE"}]
}
}
loads方法接受JSON字符串并将其转换为python字典对象(所有键都为unicode)。然后,您可以加载其他JSON对象,引用要替换的键,并分配它。然后你只需转换回JSON字符串。