【问题标题】:How to modify field in Json file using Pyhon [closed]如何使用 Python 修改 Json 文件中的字段 [关闭]
【发布时间】:2022-08-19 02:04:19
【问题描述】:

此代码汇总了“attribute_price”中的数据。

    with open(\'output/{}.json\'.format(i)) as jsonFile:
    data = json.load(jsonFile)
    tmp = data[\"price\"]
    price = sum(d[\'attribute_price\'] for d in data[\'attributes\'])

    print(price)

我需要将此金额添加到“价格”字段中。

\"attributes\": [
        {
            \"trait_type\": \"Background\",
            \"value\": \"blue\",
            \"attribute_price\": 35
        },
        {
            \"trait_type\": \"Rock\",
            \"value\": \"red\",
            \"attribute_price\": 100
        }
        }
    ],
    \"price\": 0
  • 您在自己做这件事时遇到了什么具体的技术问题?
  • 这回答了你的问题了吗? Add field to a JSON file
  • 顺便说一句,一般来说,不要将其视为试图“修改 JSON 文件中的字段”是有帮助的。将其分解为更小的步骤:您可以将 JSON 文件加载到内存中的 Python 对象中吗?你能修改那个 Python 对象吗?你能把你的 Python 对象写回 JSON 文件吗?
  • ...如果你被卡住的地方是“修改那个 Python 对象”,而你从 JSON 加载或保存到 JSON 时出现问题,那么问题实际上与 JSON 没有任何关系。考虑更小的步骤将帮助您构建更小的minimal reproducible example,并更容易在知识库中找到现有的、已回答的问题。
  • @Cloudkollektiv,这是关于 PHP 的问题,而不是 Python。

标签: python json file


【解决方案1】:

修改data 中的值,然后将其转储回文件中。

with open(f'output/{i}.json') as jsonFile:
    data = json.load(jsonFile)
    
data['price'] += sum(d['attribute_price'] for d in data['attributes'])

with open(f'output/{i}.json', 'w') as jsonFile:
    json.dump(data, jsonFile)

【讨论】:

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