Z
Z
zasara2022-01-03 12:22:03
Python
zasara, 2022-01-03 12:22:03

How to add elements to json files (python)?

I take data from API and create json file

with open("file1.json", "w") as file:
        for t in x:
            response = requests.get(url=f'...={t}')
            json.dump(response.json(), file, indent=4, ensure_ascii=False)


A json file is created with nested elements:

{

    "code": 200,

    "data": [

        {

            "key1": "KARA",

            "key2": "13"

        }

    ]

}{

    "code": 200,

    "data": [

        {

            "key1": "CRACK",

            "key2": "4"

        }

    ]

}


You need to add a root element and separate nested elements with commas.

Desired result:

[
    {
        "code": 200,
        "data": [
            {
                "key1": "KARA",
                "key2": "13"
            }
        ]
    },
    {

        "code": 200,
        "data": [
            {
                "key1": "CRACK",
                "key2": "4"
            }
        ]
    }
]


Can you please tell me how to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2022-01-03
@zasara

Obviously, you need to form a list of dictionaries and save it once, and not save the dictionary on each iteration.

D
Denis, 2022-01-13
@Sat0shi

Json -> dic, add, dic->json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question