假设我有两个JSON文件。我希望能够加载这两个文件,然后将第二个文件的条目添加到第一个文件中。这可能包括添加字段或列表条目。类似于以下示例:
file1.json:
一开始,我考虑将它们加载到字典中,尝试使用 update 这样的方法:
file1.json:
{ "fruit": [ { "name": "apple", "color": "red" }, { "name": "orange", "color": "orange" } ] }
file2.json:
{ "fruit": [ { "name": "strawberry", "color": "red", "size": "small" }, { "name": "orange", "size": "medium" } ] }
结果:
{ "fruit": [ { "name": "apple", "color": "red" }, { "name": "orange", "color": "orange", "size": "medium" }, { "name": "strawberry", "color": "red", "size": "small" } ] }
一开始,我考虑将它们加载到字典中,尝试使用 update 这样的方法:
import simplejson
filea = open("file1.json", 'r')
dicta = simplejson.loads(filea.read())
fileb = open("file2.json", 'r')
dictb = simplejson.loads(fileb.read())
filea.close()
fileb.close()
dicta.update(dictb)
由于两个字典都有“fruit”这个词条,我希望它们能够合并,但实际上它只是用dictb中的词条覆盖了dicta中的词条。
我意识到我可以编写循环代码来处理这个示例,但我正在使用的实际文件要大得多且更加复杂。在我重新发明轮子之前,我想知道是否已经有一个库可以做到这一点。值得一提的是,我正在使用Python 2.6.2。
感谢任何建议或建议!