Suppose I have two json files. I would like to be able to load both, then add the entries from the second into the first. This may include adding fields or list entries. Something like the following example:
file1.json:
{ "fruit": [ { "name": "apple", "color": "red" }, { "name": "orange", "color": "orange" } ] }
file2.json:
{ "fruit": [ { "name": "strawberry", "color": "red", "size": "small" }, { "name": "orange", "size": "medium" } ] }
result:
{ "fruit": [ { "name": "apple", "color": "red" }, { "name": "orange", "color": "orange", "size": "medium" }, { "name": "strawberry", "color": "red", "size": "small" } ] }
At first I thought to load them into dictionaries and try something like 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)
Since both dictionaries have an entry for "fruit" I was hoping that they would merge, but it simple overrides the entry in dicta with the entry in dictb.
I realize I could write code to loop through this example, but the actual files I’m using are far larger and more complicated. I was wondering if there was a library out there that did something like this already before I go reinventing the wheel. For what it’s worth, I am using Python 2.6.2.
Thanks for any advice or suggestions!
You’ll need to extend the lists checking each value. There’s no way Python can now you want to merge them based on
nameitem of dictionaries:So the
dictavariable will be: