1

I have a some variables that I need to dump as a json of the format:

{  
  "elements":[  
      {  
          "key":"foo",
          "value":"7837"
      },
      {  
          "key":"bar",
          "value":"3423"
      }
  ]
}

I am trying to figure out the right object which would give the above structure upon usin json.dumps(). I see that in python, lists give a json array where as dictionaries give a json object while using json dumps.

I am trying something like:

x={}
x["elements"]={}
x["elements"]["key"]="foo"
x["elements"]["value"]="7837"
x["elements"]["key"]="bar"
x["elements"]["value"]="3423"
json_x=json.dumps(x)

But this still gives me:

{"elements": {"key": "bar", "value": "3423"}} 

which is obviously incorrect.

How to I incorporate the correct dictionary and list structure to get to the above json?

4
  • Why don't you just use x = {"elements":[{"key":"foo", "value":"7837"}, {"key":"bar", "value":"3423"}]} ? Commented Oct 25, 2016 at 1:30
  • That indeed is usable. I am just trying to better understand the python object/json structure. But what you said works! Commented Oct 25, 2016 at 1:32
  • 1
    elements key has another array (Python list) as a value, not another object. That was your mistake. Commented Oct 25, 2016 at 1:40
  • 1
    The Python structure that dumps turns into that JSON... is the one that loads creates from that JSON. Commented Oct 25, 2016 at 1:41

1 Answer 1

1

Why don't you just use literal?

x = {
    "elements": [
        {"key":"foo", "value":"7837"},
        {"key":"bar", "value":"3423"}
    ]
}

To fix your code, you need to use a list literal ([]) when assigning to elements dictionary entry:

>>> x = {}
>>> x["elements"] = []  # <--- 
>>> x["elements"].append({})
>>> x["elements"].append({})
>>> x["elements"][0]["key"]="foo"
>>> x["elements"][0]["value"]="7837"
>>> x["elements"][1]["key"]="bar"
>>> x["elements"][1]["value"]="3423"
>>> json.dumps(x)
'{"elements": [{"value": "7837", "key": "foo"}, {"value": "3423", "key": "bar"}]}'

But, it's hard to read, maintain.

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

Comments

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.