简体   繁体   English

JSON文件特定行编辑

[英]JSON file specific line editing

I'd like to ask what is the best way to replace specific line in multiple json files.我想问一下在多个 json 文件中替换特定行的最佳方法是什么。 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

So item['BgTest'] does not exist in the items you're iterating through.所以item['BgTest']在您迭代的项目中不存在。 I think you want to replace the "Untitled" value with the value "BgTest" .我想你想用值"BgTest"替换"Untitled"值。 In that case, replace the for loop with the one below:在这种情况下,将 for 循环替换为以下循环:

for item in data['attributes']:
    if item['value'] == 'Untitled':
        item['value'] = 'BgTest'
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. BgTest不是您发布的示例的有效密钥。 If you only have that key in certain rows of the list you can not use it in the for loop.如果您在列表的某些行中只有该键,则不能在 for 循环中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM