如何在python旧版本中使用有序词典?
答案 0 :(得分:1)
我将使用jsonmerge
合并您的json文件。它很好地处理了JSON文件的合并。
您可以使用pip install jsonmerge
安装此库。
演示:
from json import loads
from json import dump
from jsonmerge import merge
# Store your json files here
# If all of them exist in directory, you can use os.listdir() instead
json_files = ['file1.json', 'file2.json']
with open('merged.json', 'w') as json_out:
# Store updated results in this dict
data = {}
for file in json_files:
with open(file, 'rb') as json_file:
json_data = loads(json_file.read())
# Update result dict with merged data
data.update(merge(data, json_data))
dump(data, json_out, indent=4)
其中给出了以下 merged.json :
{
"head-param": "foo",
"head-param1": "bar",
"head-sub-param": {
"head-sub-param1": "foo",
"head-sub-param2": "bar"
},
"body": {
"name1": {
"value": "foo",
"option": "bar",
"bar": "bar",
"foo": "foo",
"baz": "baz"
},
"name22": {
"value1": "foo1",
"option1": "bar1",
"bar1": "bar1",
"foo1": "foo1",
"baz1": "baz1"
}
}
}
答案 1 :(得分:1)
from collections import OrderedDict
from functools import partial
import json
import sys
if sys.version_info < (3,6): # Pre Python 3.6?
ordered_json_load = partial(json.load, object_pairs_hook=OrderedDict)
else:
ordered_json_load = json.load
with open('file1.json') as finput1, open('file2.json') as finput2:
# Merge data from files.
merged = ordered_json_load(finput1)
merged['body'].update(ordered_json_load(finput2)['body'].items())
# Write the merged data to an output file.
with open('output.json', 'w') as foutput:
json.dump(merged, foutput, indent=4)
产生的输出文件的内容:
{
"head-param": "foo",
"head-param1": "bar",
"head-sub-param": {
"head-sub-param1": "foo",
"head-sub-param2": "bar"
},
"body": {
"name1": {
"value": "foo",
"option": "bar",
"bar": "bar",
"foo": "foo",
"baz": "baz"
},
"name22": {
"value1": "foo1",
"option1": "bar1",
"bar1": "bar1",
"foo1": "foo1",
"baz1": "baz1"
}
}
}
答案 2 :(得分:1)
您可以编写一些递归函数:
def update_nested_dict(dict_1, dict_2):
"""Mutate dict_1 by updating it with all values present in dict_2."""
for key, value in dict_2.items():
if key not in dict_1:
# Just add the value to dict_1
dict_1[key] = value
continue
if isinstance(value, dict):
# If this is a dict then let's recurse...
update_nested_dict(dict_1[key], value)
调用update_nested_dict(json1, json2)
会将json1
更改为:
{'head-param': 'foo',
'head-param1': 'bar',
'head-sub-param': {'head-sub-param1': 'foo', 'head-sub-param2': 'bar'},
'body': {'name1': {'value': 'foo',
'option': 'bar',
'bar': 'bar',
'foo': 'foo',
'baz': 'baz'},
'name22': {'value1': 'foo1',
'option1': 'bar1',
'bar1': 'bar1',
'foo1': 'foo1',
'baz1': 'baz1'}}}