A
A
Andrey Smirnov2020-01-24 20:43:18
Python
Andrey Smirnov, 2020-01-24 20:43:18

How to change data in JSON from Python?

There is some valid JSON file. Example:

{
    "example1": "hi",
    "example2": "hihi" 
}

How can I change the value of a specific element/key (eg example1) in Python. Or implement full read, change in dump and overwrite

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-01-24
@trapwalker

Yes, JSON is not practical to change directly on disk. You need to load it, parse it, replace the value, then serialize the data again to JSON and save it to disk.

import json
with open('myfile.json') as f:
    data = json.load(f)
data['example1'] = 'bye'
with open('myfile.json', 'w') as f:
    json.dump(data, ensure_ascii=False, indent=4)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question