I’ve 3 json files. The first one have only one sentence (file1.json):
JavaScript
x
2
1
"Car":"Black"
2
The second one have only one sentence(file.json):
JavaScript
1
2
1
"Car":"White"
2
And the third one is a list of dictionaries (example.json)
JavaScript
1
12
12
1
[
2
{
3
"Person": "Alex",
4
"Age":3
5
},
6
7
{ "Country": "France",
8
"Job":"None"
9
10
}
11
]
12
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
JavaScript
1
3
1
from jsonmerge import merge
2
result = merge(file1.json or file2.json, example.json)
3
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.
JavaScript
1
14
14
1
import json
2
with open('example.json', 'r') as f:
3
example = json.load(f)
4
with open('file1.json', 'r') as f:
5
file1 = json.load(f)
6
with open('file1.json', 'r') as f:
7
file2 = json.load(f)
8
if file1:
9
example[0]['Car'] = file1['Car']
10
elif file2:
11
example[0]['Car'] = file2['Car']
12
with open('example2.json', 'w') as f:
13
json.dump(example, f, indent=4)
14