Home > Mobile >  Appending json object inside the main block in Python
Appending json object inside the main block in Python

Time:07-10

I'm trying to create a json file from python. I have the following code:

import json

PARENTS = ["parent1", "parent2"]
data = []
for parent in PARENTS:
    data.append(
                    {
                        parent:
                        {
                            "child1": "value1",
                            "child2": "value2"
                        }
                    }
                )
with open("file.json", "w") as f:
    json.dump(data, f, indent=4)

The output of this is the following json. It creates 2 separate blocks.

[
    {
        "parent1": {
            "child1": "value1",
            "child2": "value2"
        }
    },
    {
        "parent2": {
            "child1": "value1",
            "child2": "value2"
        }
    }
]

However I need the output within a single block like below:

{
    "parent1": {
        "child1": "value1",
        "child2": "value2"
    },
    "parent2": {
        "child1": "value1",
        "child2": "value2"
    }
}

How can I get it in the format I need. Thanks!

CodePudding user response:

make data a dict instead of a list and set the parent value

import json

PARENTS = ["parent1", "parent2"]
data = {}
for parent in PARENTS:
    data[parent] = {
                 "child1": "value1",
                 "child2": "value2"
    }

with open("file.json", "w") as f:
    json.dump(data, f, indent=4)

CodePudding user response:

Use a dictionary instead of a list

import json

PARENTS = ["parent1", "parent2"]  
data = {}  
for parent in PARENTS:  
    data[parent]=\
                        {
                            "child1": "value1",
                            "child2": "value2"
                        }

             
with open("file.json", "w") as f:
    json.dump(data, f, indent=4)

  • Related