2

I'm new to python and json files and I have a json file which has only one attribute and I want to update each object in the file by adding a new attribute, my json file looks like:

[
{"marka": "تويوتا"},
{"marka": "شيفروليه"},
{"marka": "نيسان"}
]

and I want it to be something like:

[
{"marka": "تويوتا" , "tag" : "MANF"},
{"marka": "شيفروليه" , "tag" : "MANF"},
{"marka": "نيسان" , "tag" : "MANF"}
]

I tried this code but it gives me an error:

with open("haraj_marka_arabic.json", "r") as jsonFile:
     data = json.load(jsonFile)

tmp = data["tag"]
data["tag"] = "MANF"

with open("haraj_marka_arabic.json", "w") as jsonFile:
    json.dump(data, jsonFile)

The error I had is:

TypeError: list indices must be integers, not str

3 Answers 3

3

Your JSON is a list of dictionaries (in Python speak), each containing the 'tag' element, so you need to iterate through those list items and assign the new value to this 'tag' key:

with open("haraj_marka_arabic.json", "r") as jsonFile:
     data = json.load(jsonFile)

for d in data:
    d["tag"] = "MANF"

with open("haraj_marka_arabic.json", "w") as jsonFile:
    json.dump(data, jsonFile)
Sign up to request clarification or add additional context in comments.

Comments

1

your JSON file contains a list of dictionaries, to update each dict from your data list you can use:

for d in data:
    d['tag'] = "MANF"

then you can dump your data to a file:

with open("haraj_marka_arabic.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Comments

0
### given this is your sample object (Dictionary):
  data = [
         {"marka": "تويوتا"},
         {"marka": "شيفروليه"},
         {"marka": "نيسان"}
         ]
##end of sample object (Dictionary)

with open("haraj_marka_arabic.json", "r") as jsonFile: ## Assume data contains the object (dictionary) above
     data = json.load(jsonFile)

your error is here: your data structure is an array (list) of objects (dictionaries), you're accessing "skipping the array (list)"

for tmp in data:
 tmp["tag"] = "MANF"


with open("haraj_marka_arabic.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Post edited to reflect the different terminology choice between Python and JSON.

Comments

Your Answer

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