Home > Software design >  JSON file specific line editing
JSON file specific line editing

Time:07-22

I'd like to ask what is the best way to replace specific line in multiple json files. In everyfile its the same line that needs to be replaced. enter image description here

import json
with open('3.json') as f:
    data = json.load(f)

for item in data['attributes']:
    item['value'] = item['value'].replace("Untitled", item['BgTest'])

with open('3.json', 'w') as d:
    json.dump(data, d)

I tried this code I found but it keeps giving me an error:

"/Users/jakubpitonak/Desktop/NFT/Gnomes Collection/ART-GEN-TUTORIAL 2.0/bin/python" /Users/jakubpitonak/PycharmProjects/pythonProject1/update.py
Traceback (most recent call last):
  File "/Users/jakubpitonak/PycharmProjects/pythonProject1/update.py", line 25, in <module>
    item['value'] = item['value'].replace("Untitled", item['BgTest'])
KeyError: 'BgTest'

Process finished with exit code 1

CodePudding user response:

So item['BgTest'] does not exist in the items you're iterating through. I think you want to replace the "Untitled" value with the value "BgTest". In that case, replace the for loop with the one below:

for item in data['attributes']:
    if item['value'] == 'Untitled':
        item['value'] = 'BgTest'

CodePudding user response:

import json
with open('3.json') as f:
    data = json.load(f)

for item in data['attributes']:
    item['value'] = "Your value here"

with open('3.json', 'w') as d:
    json.dump(data, d)

BgTest is not a valid key for the example you posted. If you only have that key in certain rows of the list you can not use it in the for loop.

  • Related