[英]How to modify JSON values by taking text file content?
I am trying to modify JSON values by taking content from text file but it write the value as the last value of txt file.我试图通过从文本文件中获取内容来修改 JSON 值,但它将值写入 txt 文件的最后一个值。 What I want to do is to write every line from the text file as a value for
item['ax']
.我想要做的是将文本文件中的每一行都写为
item['ax']
。 (You can see it in the code.) (你可以在代码中看到它。)
import json, os
with open('res.json', 'r') as file:
json_data = json.load(file)
try:
with open('x.txt', 'r') as file:
line_x = file.read().splitlines()
for xv in line_x:
for item in json_data['resources'][1:]:
item['ax'] = xv
except:
continue
os.chdir('../')
with open('fixed.json', 'w') as out:
json.dump(json_data, out)
Here is a screenshot showing the wrong result:这是显示错误结果的屏幕截图:
449
is the last value in the text file. 449
是文本文件中的最后一个值。
Your problem is with this code:你的问题是这段代码:
for xv in line_x:
for item in json_data['resources'][1:]:
item['ax'] = xv
You are taking the first line of your text file, assigning to xv and then replacing every item['ax'] throughout the json file with that value.您正在获取文本文件的第一行,将其分配给xv ,然后将整个 json 文件中的每个item['ax']替换为该值。 Then you get the next line of the text file and replace all the item['ax'] in the json file with that new value, and so on, until they all have the value of the last item in the text file.
然后你得到文本文件的下一行,并将 json 文件中的所有item['ax']替换为新值,依此类推,直到它们都具有文本文件中最后一项的值。
Perhaps something like this would work better:也许这样的事情会更好:
line_x = file.read().splitlines()
xv = [line for line in line_x]
for item in json_data['resources'][1:]:
item['ax'] = xv.pop(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.