Magno Alberto
Magno Alberto

Reputation: 668

how to merge multiple json files into a single file

Within a directory, I can have several files, taking as an example...

chunk26.4ec7e9b2.json

{
    "/css/app.css": "/css/app.css?id=0f487b3ea1da478a47ce"
}

chunk57.9bc6ea1f.json

{
    "/js/app.js": "/js/app.js?id=f3eda47538cccd3ab358",
    "/js/empresa.js": "/js/empresa.js?id=2e389af5c75f398c7c97",
    "/js/passwordreset.js": "/js/passwordreset.js?id=2f48c7b9a250fb573381",
    "/js/prelogin.js": "/js/prelogin.js?id=4835300bf9075df04126"
}

How is it possible to merge these files, as a valid json file, remembering that I can have N files and their names can be anything but always with the json extension, and this result will be saved in the current directory.

expected outcome

{
    "/js/app.js": "/js/app.js?id=f3eda47538cccd3ab358",
    "/js/empresa.js": "/js/empresa.js?id=2e389af5c75f398c7c97",
    "/js/passwordreset.js": "/js/passwordreset.js?id=2f48c7b9a250fb573381",
    "/js/prelogin.js": "/js/prelogin.js?id=4835300bf9075df04126",
    "/css/app.css": "/css/app.css?id=0f487b3ea1da478a47ce"
}

Important note is that the last line must not have a comma.

enter image description here

As I'm still learning python, I got a part, at least I could see each line

import glob;
files=[];

for filename in glob.glob("*.json"):
    print(filename);
    files.append(filename);

print(files);

for filename in files:
    with open(filename, "r") as a_file:
          for line in a_file:
              print(line)

... but I really don't know if it is the most functional or practical way to achieve the expected result

Upvotes: 0

Views: 3679

Answers (2)

James Shapiro
James Shapiro

Reputation: 6196

import json

files = ['file1.json', 'file2.json', 'file3.json']
combined_json = {}
for filename in files:
    with open(filename) as f:
        file_json = json.load(f)
    combined_json.update(file_json)

Upvotes: 1

Timur Mishagin
Timur Mishagin

Reputation: 36

You can use a small util called package-json-merge. This is a nodejs lib, but I think it is worth to mention it here.

Note that the order of files matters when we talk about similar fields

In your case it might be something like this

package-json-merge chunk57.9bc6ea1f.json chunk26.4ec7e9b2.json > result.json

Upvotes: 1

Related Questions