[Fixed]-Python JSON nested key value pair parsing

1👍

When you get variable from the request it isn’t just ‘treated’ as a string… is is a string.

So you need to:

json.loads(variable)

before adding it to the dict which is later serialized to json.

i.e.

variable = json.loads(request.GET.get('name', '{}'))
payload = {
    'var1': var1,
    'variable': variable,
}
r = requests.post("URL",data= json.dumps(payload),headers={'Authorization': obj.header, 'Content-type': 'application/json'}, proxies=getProxyDict())

0👍

You have presumably already dumped variable to a JSON string. Don’t do that; leave it as a dict, and dump the whole thing in one go.

0👍

import json

variable = {'name': 'ABC', 'Id': '1'}

payload = {
    'var1': 'foo',
    'variable': variable,
}

print json.dumps(payload, indent=4)

results to

{
    "variable": {
        "name": "ABC", 
        "Id": "1"
    }, 
    "var1": "foo"
}

which is perfectly json. But, you may need to set your headers according to the API you’re talking to.

request = requests.get('myurl', headers={'accept': 'application/json'})
json_data = request.json()
# manipulate json_data
request = requests.post('myurl', headers={'content-type': 'application/json'}, json=json_data)
👤ferdy

0👍

Few things I would like to point here.

variable= "{'name': 'ABC', 'Id': '1'}"

This is NOT a valid json string.

variable= '{"name": "ABC", "Id": "1"}'

This is a valid json string.

So first before attaching this variable to payload dict you need to convert it to a python dict like this.

variable = json.loads(variable)

This will create variable something like this.

{u'name': u'ABC', u'Id': u'1'}

Now you can go ahead and add this to your payload dict and continue what you are doing.

Leave a comment