2

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"}
]}
1
  • 4
    What you posted is invalid JSON. You can't have something like ["x": blah]. The colon can only occur inside {}, not directly inside []. Commented Sep 16, 2015 at 2:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you please be more explicit with your code example to help me out? I think I understand where you are going but I could use a concrete example.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.