N
N
nnikolyaa2020-06-24 21:47:14
Python
nnikolyaa, 2020-06-24 21:47:14

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

2 answer(s)
S
ScriptKiddo, 2020-06-24
@nnikolyaa

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')

old
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')

test_out.json
{"2000000003": {"amv": true, "amvl": true, "whoa": true}}
{"2000000004": {"amv": false, "amvl": true, "whoa": true}}

A
Alexander, 2020-06-24
@NeiroNx

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

if it's in a file:
Three cycles is tough, you can do the same - just change the file later.
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 question

Ask a Question

731 491 924 answers to any question