简体   繁体   中英

How to Make Nested JSON Object with Python

I need to make JSON output that looks like the following

{   "items": [
     "number": {
       "value": 23
       "label": test
    }
]
}

I've done something similar with the code below but I can't figure out how I need to nest number under items.

#!/usr/bin/python

import json

myjson = {'items':[]}
d = {}
d['value'] = 23
d['label'] = "test"
myjson.get('items').append(d)
output = json.dumps(myjson)
print output

That gives me

{
"items": [{
  "value": 23, 
  "label": "test"}
]}

Your input JSON isn't proper, it should be something like:

{ "items": 
    [ 
       {
       "number": 
           {
           "value": 23,
           "label": "test"
           }
       } 
    ] 
}

Besides that it can get messy, but accessing the resultant dict is intuitive.

 jdict = json.loads(yourjson)
 jdict['items'] => [{"number":{...}}]
 jdict['items'][0] => {"number":{...}}
 jdict['items'][0]['number']['value'] => 23

Edit:

Think you actually just wanted this:

myjson.get('items').append({'number': d})

You have to append a dictionary, not entries of a dictionary to items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM