I have multiple json files containing a json array object in the following format.
[
{
"appId": "1",
"userName": "zrqxnav2ktobg5ph4y6inxm4t22oqxnj",
"appManagerError": {
"errorCode": "",
"errorMsg": ""
},
"endpoints": [
{
"path": "unknown"
}
]
}
]
I would like to merge all the json files [in the same format] in a single file. something like this.
[
{
"appId": "1",
"userName": "zrqxnav2ktobg5ph4y6inxm4t22oqxnj",
"appManagerError": {
"errorCode": "",
"errorMsg": ""
},
"endpoints": [
{
"path": "unknown"
}
]
},
{
"appId": "2",
"userName": "zrjsjdsj34sdkjskt22oqxnj",
"appManagerError": {
"errorCode": "",
"errorMsg": ""
},
"endpoints": [
{
"path": "known"
}
]
}
]
Fortunately, I was able to get this done in the shell using jq.
cat temp1.json temp2.json | jq -s add > temp.json || exit $?
But I can't find anything similar in python.
import json
content = []
filenames = ['temp1.json', 'temp2.json']
for filename in filenames:
with open(filename, 'r') as f:
content += json.load(f)
with open('temp.json', 'w') as f:
json.dump(content, f, indent=4)
You can use that following code assuming that json_list
is a list containing all yours stringified json files
from itertools import chain
import json
dictios = list()
for e in json_list:
dictios.append(json.loads(e))
merged = json.dumps(dict(chain.from_iterable(d.items() for d in dictios)))
merged
will contain a stringified json which is the fusion of all your previous json files
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.