13
votes

So I have a Python code which returns a JSON string like this one:

'{"X": "value1", "Y": "value2", "Z": [{"A": "value3", "B": "value4"}]}'

What I want to do is to print and/or return (in Python) "value 3" in order to use it. Also assign it to a variable so I can work with it later on.

How can I do this?

2
Sorry for the mistake on the code!! thnx! - Jmlevick
NOTE: I'm using the "simplejson" module to parse the data - Jmlevick
Your input still is no valid JSON. value1 and value4 must be inside quotes. Even simplejson can't decode your input. - user647772
Please post some of the code you are trying so we don't have to guess which module you use. - user647772
Btw, simplejson is same as the json library. stackoverflow.com/questions/712791/… - amit

2 Answers

21
votes
>>> import json
>>> a = json.loads('{"X":"value1","Y":"value2","Z":[{"A":"value3","B":"value4"}]}')
>>> a
{'Y': 'value2', 'X': 'value1', 'Z': [{'A': 'value3', 'B': 'value4'}]}
>>> a["Z"][0]["A"]
'value3'
4
votes

OK, I assume your JSON looks like this (note the " around each value):

{"X":"value1", "Y":"value2", "Z":[{"A":"value3", "B":"value4"}]}

Then you can do this:

import json
j = '{"X":"value1", "Y":"value2", "Z":[{"A":"value3", "B":"value4"}]}'
k = json.loads(j)
assert k["Z"][0]["A"] == "value3"

Edit: Even simplejsoncan't decode your original input.

>>> import simplejson
>>> s1 = '{"X":value1,"Y":"value2","Z":[{"A":"value3","B":value4}]}'
>>> simplejson.loads(s1)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)
>>> s2 = '{"X":"value1", "Y":"value2", "Z":[{"A":"value3", "B":"value4"}]}'
>>> print simplejson.loads(s2)["Z"][0]["A"]
value3