Set item using data['id'] = ....
import json
with open('data.json', 'r+') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=4)
f.truncate() # remove remaining part
Answer from falsetru on Stack OverflowSet item using data['id'] = ....
import json
with open('data.json', 'r+') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=4)
f.truncate() # remove remaining part
falsetru's solution is nice, but has a little bug:
Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.
I solved that by replacing the original file.
import json
import os
filename = 'data.json'
with open(filename, 'r') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
os.remove(filename)
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
i dont really know how to edit json files with python, and I've got a list in a json file that id like to add things to/remove things from. how do I do so?
How do I edit .json data with python? - Stack Overflow
(absolute beginner) how do I run a Python script & how do I edit JSON?
Modify JSON - what is the best approach?
editing json files
I got the solution after a lot testing and searching.
The correct code is
with open('filename.json', 'r') as f:
json_data = json.load(f)
json_data['some_id'][0]['embed'] = 'Some string'
with open('filename.json', 'w') as f:
json.dump(json_data, f, indent=2)
It neither duplicate any data nor delete any existing data just change. OMG I got it finally.
json_data becomes a dictionary with the same structure as your JSON. To access 'inner' elements, you just have to navigate the dictionary structure.
See comment below.
with open('filename.json', 'r') as f:
json_data = json.load(f)
json_data['some_id'][0]['embed'] = 'Some string' # On this line you needed to add ['embed'][0]
with open('filename.json', 'w') as f:
json.dump(json_data, f, indent=2)
I've got a JSON file that needs to be sent as a POST API request but I need to modify the JSON file first, e.g. nest some key-value pairs under a parent name (that needs to be added too), rename some keys, etc.
As far as I understand, this can be relatively easily done if we use dataframes. What is the best way to approach this - convert json to dataframe, make these edits and then convert it back to json? or make these edits in a dictionary?