Home > Software design >  Separate large JSON object into many different files
Separate large JSON object into many different files

Time:03-22

I have a JSON file with 10000 data entries like below in a file.

{
    "1":{
        "name":"0",
        "description":"",
        "image":""
    },
    "2":{
        "name":"1",
        "description":"",
        "image":""
     },
     ...
}

I need to write each entry in this object into its own file.

For example, the output of each file looks like this:

1.json

{
  "name": "",
  "description": "",
  "image": ""
}

I have the following code, but I'm not sure how to proceed from here. Can anyone help with this?

import json
  
with open('sample.json', 'r') as openfile:
  
    # Reading from json file
    json_object = json.load(openfile)

CodePudding user response:

You can use a for loop to iterate over all the fields in the outer object, and then create a new file for each inner object:

import json

with open('sample.json', 'r') as input_file:
    json_object = json.load(input_file)
    for key, value in json_object.items():
        with open(f'{key}.json', 'w') as output_file:
            json.dump(value, output_file)
  • Related