1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you I noticed that myself and manage to resolve it by doing json_data = json.load(myfile)[0] but thank you so much for your input, would you know if i need to use the copy library to copy each Array after editing in a new file but with different data each time? for example, if i was to copy that Array 10 times but with different values in each object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.