【问题标题】:How to modify JSON values by taking text file content?如何通过获取文本文件内容来修改 JSON 值?
【发布时间】:2020-04-20 05:55:05
【问题描述】:

我试图通过从文本文件中获取内容来修改 JSON 值,但它将值写入 txt 文件的最后一个值。我想要做的是将文本文件中的每一行写为item['ax'] 的值。 (你可以在代码中看到。)

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)

这是显示错误结果的屏幕截图:

449 是文本文件中的最后一个值。

【问题讨论】:

  • 裸露的except: 子句可能隐藏了一个问题。我强烈建议您避免这样做,并明确列出可能发生的异常(或至少打印或记录发生的异常——即except Exception as exc:,然后在其下方缩进print(exc)

标签: python arrays json python-3.x


【解决方案1】:

你的问题在于这段代码:

for xv in line_x:
    for item in json_data['resources'][1:]:
        item['ax'] = xv

您正在获取文本文件的第一行,分配给 xv,然后用该值替换整个 json 文件中的每个 item['ax']。然后获取文本文件的下一行,并将 json 文件中的所有 item['ax'] 替换为该新值,依此类推,直到它们都具有最后一项的值在文本文件中。

也许这样的事情会更好:

line_x = file.read().splitlines()
xv = [line for line in line_x]
for item in json_data['resources'][1:]:
    item['ax'] = xv.pop(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多