44

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.

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
swoosh
  • 639
  • 2
  • 9
  • 17
  • 4
    Technically speaking, this is not a JSON object (even though it's formatted in the JSON style), it's a python dict. It's not "coming out right with brackets and quotes" because you are `append()`ing a string to the dictionary value `[]`. – Joel Cornett Jun 05 '12 at 10:04

3 Answers3

59
jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
10

Just add the dictionary as a dictionary object not a string :

jsobj["a"]["b"]["e"].append(dict(f=var3))

Full source :

var1 = 11
var2 = 32
jsonobj = {"a":{"b":{"c": var1,
                     "d": var2,
                     "e": [],
                    },
               },
           }
var3 = 444
jsonobj["a"]["b"]["e"].append(dict(f=var3))

jsonobj will contain :

{'a': {'b': {'c': 11, 'd': 32, 'e': [{'f': 444}]}}}
Munim Munna
  • 17,178
  • 6
  • 29
  • 58
PhE
  • 15,656
  • 4
  • 23
  • 21
2
jsonobj["a"]["b"]["e"] += [{'f': var3, 'g' : var4, 'h': var5}, 
                           {'f': var6, 'g' : var7, 'h': var8}]
katzenversteher
  • 810
  • 6
  • 13
  • 2
    There is [extend](http://docs.python.org/tutorial/datastructures.html#more-on-lists) method for that. – DrTyrsa Jun 05 '12 at 10:21