Search code examples
pythonjsonline

JSON file specific line editing


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

Solution

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