Answer the question
In order to leave comments, you need to log in
How to replace json value?
I can't find a proper guide. For example, how to write in 2000000004 amv=false
{"2000000003": {"amv": true, "amvl": true, "whoa": true}}
{"2000000004": {"amv": true, "amvl": true, "whoa": true}}
Answer the question
In order to leave comments, you need to log in
test.json
{"2000000003": {"amv": true, "amvl": true, "whoa": true}}
{"2000000004": {"amv": true, "amvl": true, "whoa": true}}
import json
target_id = '2000000004'
result = []
with open('test.json', encoding='UTF-8') as source, \
open('test_out.json', 'w', encoding='UTF-8') as out:
for line in source:
parsed_json_line = json.loads(line)
if target_id in parsed_json_line.keys():
parsed_json_line[target_id]['amv'] = False
out.write(f'{json.dumps(parsed_json_line)}\n')
import json
result = []
with open('test.json', encoding='UTF-8') as f:
for line in f:
result.append(json.loads(line))
target_id = '2000000004'
for i, item in enumerate(result):
if target_id in item.keys():
result[i][target_id]['amv'] = False
with open('test_out.json', 'w', encoding='UTF-8') as f:
for item in result:
f.write(f'{json.dumps(item)}\n')
{"2000000003": {"amv": true, "amvl": true, "whoa": true}}
{"2000000004": {"amv": false, "amvl": true, "whoa": true}}
The fact that you have not quite valid JSON
import json
data = json.loads("""
{"2000000003": {"amv": true, "amvl": true, "whoa": true},
"2000000004": {"amv": true, "amvl": true, "whoa": true}}
""")
data["2000000004"]["amv"] = True
key = "2000000004"
with open("file.json","r") as inp, open("temp.json", "w") as out:
for line in inp:
linej=json.loads(line)
if key in linej:
linej[key]["amv"] = False
line = json.dumps(linej)+"\n"
out.write(line)
os.remove("file.json")
os.rename("temp.json","file.json")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question