Puo
Puo

Reputation: 11

Python json How to add data

I don't speak English well So the question may be a bit odd

{
    "arg1": {
        "1": "1",
        "2": "2"
    },
    "arg2": {
        "1": "1",
        "2": "2"
    },
    "arg3": {
        "1": "1",
        "2": "2"
    }
}

I want to store data this way. What should I do?

json_data = {arg3: {"1": "1", "2": "2"}}
with open(f'./Json/test.json', 'w', encoding='utf-8') as make_file:
    json.dump(json_data, make_file, ensure_ascii=False ,indent="\t")

Is this right? I would appreciate it if you let me know.

I don't know what to do by deleting the original content.

Upvotes: 0

Views: 49

Answers (1)

thekid77777
thekid77777

Reputation: 391

Your code works fine. The only problem I see when your running it is that that arg3 needs to be written as "arg3" in double quotes (single quotes are invalid in json) unless you have a value for it defined previously.

json_data = {"arg3": {"1": "1", "2": "2"}}

Make that change, and you should be able to load and properly display your JSON with:

with open(f'output.json') as f:
    a = json.load(f)
    print(json.dumps(a, indent="\t"))

If you do the json.dumps() you get a properly formatted json which you can then call print on to display.

Upvotes: 1

Related Questions