Skip to content
Advertisement

Merge two json files implementing a row in a specific position

I’ve 3 json files. The first one have only one sentence (file1.json):

"Car":"Black"

The second one have only one sentence(file.json):

"Car":"White"

And the third one is a list of dictionaries (example.json)

[
  {
    "Person": "Alex",
     "Age":3
},

{ "Country": "France",
  "Job":"None"

}
]

And I want to insert the sentence of file1.json or file2.json just above "Person": "Alex" in example.json. I say file1.json or file2.json because only one exits depending on the circumstances.

I’ve tried this

from  jsonmerge import merge
result = merge(file1.json or file2.json, example.json)

But it’s difficult for me to insert that row wherever I want.

Advertisement

Answer

jsonmerge is not really intended to do that. I’m just guessing what you’re really trying to accomplish but I think you better just load the JSON via the Python internals and then form the desired JSON manually.

import json
with open('example.json', 'r') as f:
    example = json.load(f)
with open('file1.json', 'r') as f:
    file1 = json.load(f)
with open('file1.json', 'r') as f:
    file2 = json.load(f)
if file1:
    example[0]['Car'] = file1['Car']
elif file2:
    example[0]['Car'] = file2['Car']
with open('example2.json', 'w') as f:
    json.dump(example, f, indent=4)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement