Reputation: 21
Firstly, here is my JSON file structure
[{
"title": "Reference Addition",
"ref_date": 20200110,
"country": "ASIA",
"ref_internal": "1",
"ref_external": "1"
}]
I have code where I have successfully loaded the file in Python. I want to change the value of country and save it to a new file.
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)
But unfortunately I keep getting
AttributeError: module 'json' has no attribute 'tree'
searched something online after which i manage to resolve that Error but now hitting this Error
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)
error now with full traceback is
Traceback (most recent call last):
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>
Apologies if any detail is not correct but please let me know so i can provide
Upvotes: 1
Views: 68
Reputation: 11
The issue is with the JSON file structure. It looks like your JSON file is an array of objects, each containing the properties you listed. In order to access the country property, you need to first access the object within the array. You can do this by specifying the index of the object, like this:
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)
This will change the value of the country property of the first object in the array to "AFRICA".
Also, in your code, it is not necessary to use json.tree, it is just json.dump to save the data in the file.
Upvotes: 1