How to print particular JSON value in Python?

前端 未结 2 551
傲寒
傲寒 2020-12-16 17:16

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

\'{"X": "value1", "Y": "value2", "Z": [{&         


        
相关标签:
2条回答
  • 2020-12-16 17:57
    >>> 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'
    
    0 讨论(0)
  • 2020-12-16 17:59

    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
    
    0 讨论(0)
提交回复
热议问题