Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python append to array in json object

I have the following json object in python:

jsonobj = {           "a": {               "b": {                       "c": var1,                       "d": var2,                       "e": [],                    },                  },             } 

And I would like to append key-value elements into "e", but can't figure out the syntax for it. I tried appending with the following, but it doesn't come out right with the brackets and quotes:

jsobj["a"]["b"]["e"].append("'f':" + var3) 

Instead, I want "e" to be the following:

"e":[        {"f":var3, "g":var4, "h":var5},        {"f":var6, "g":var7, "h":var8},     ] 

Does anyone know the right way to append to this json array? Much appreciation.

like image 836
swoosh Avatar asked Jun 05 '12 09:06

swoosh


People also ask

How do I add items to a JSON array in Python?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

How do you update a JSON object in Python?

Updating a JSON object in Python is as simple as using the built-in update() function from the json package we have imported. The update method is used to add a new key-value pair to the JSON string that we declared in our code.


1 Answers

jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5}) jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8}) 
like image 103
DrTyrsa Avatar answered Sep 20 '22 09:09

DrTyrsa