【问题标题】:Using Python to input a JSON input file, to Edit JSON object and same as new file使用 Python 输入 JSON 输入文件,编辑 JSON 对象并与新文件相同
【发布时间】:2023-01-13 04:37:46
【问题描述】:

首先,这是我的 JSON 文件结构

[{
"title": "Reference Addition",
"ref_date": 20200110,
"country": "ASIA",
"ref_internal": "1",
"ref_external": "1"
}]

我有在 Python 中成功加载文件的代码。我想更改国家/地区的值并将其保存到新文件中。

with open('myfile.json', 'r') as f:
 json_data = json.load(f)
json_data['country'] = 'AFRICA'

with open('myfile.json', 'w') as f:
json.dump(json_data, f, indent=2)

但不幸的是我不断得到

AttributeError: module 'json' has no attribute 'tree'

在网上搜索了一些东西,之后我设法解决了那个错误,但现在遇到了这个错误

import json
myfile = ('JSON\TRADE.json')

with open (myfile, 'r') as myfile: json_data = json.load(myfile) json_data['country'] = 'AFRICA'
 json.tree.dump(json_data, indent=4)
with open(myfile, 'w') as f: json.dump(json_data, f, indent=4)

现在带有完整回溯的错误是

追溯(最近一次通话):

File "c:\AUTOMATION\Data Creation\JSON\EDIT.py", line 7, in json_data['country'] = 'AFRICA' TypeError: list indices must be integers or slices, not str PS C:\AUTOMATION\Data Creation>

如果有任何细节不正确,我们深表歉意,但请告诉我,以便我提供

【问题讨论】:

    标签: python json


    【解决方案1】:

    问题出在 JSON 文件结构上。看起来您的 JSON 文件是一个对象数组,每个对象都包含您列出的属性。为了访问 country 属性,您需要首先访问数组中的对象。您可以通过指定对象的索引来执行此操作,如下所示:

    with open(myfile, 'r') as f:
        json_data = json.load(f)
        json_data[0]['country'] = 'AFRICA'
    
    with open(myfile, 'w') as f:
        json.dump(json_data, f, indent=4)
    
    

    这会将数组中第一个对象的国家/地区属性值更改为“AFRICA”。

    此外,在您的代码中,没有必要使用 json.tree,只需使用 json.dump 即可将数据保存在文件中。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      相关资源
      最近更新 更多