user7856770
user7856770

Reputation:

Update json object by adding new attribute in python

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

Upvotes: 2

Views: 8764

Answers (3)

DDS
DDS

Reputation: 2479

### 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.

Upvotes: 0

kederrac
kederrac

Reputation: 17322

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)

Upvotes: 1

dspencer
dspencer

Reputation: 4471

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)

Upvotes: 3

Related Questions