How to print a specific JSON value in Python?

So, I have Python code that returns a JSON string like this:

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

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

How can i do this?

+7
source share
2 answers
 >>> 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' 
+12
source

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 simplejson cannot 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 
+3
source

All Articles