lichengwu lichengwu - 1 year ago 64
JSON Question

How can I use python finding particular json value by key?

There is a json like this:

"P1": "ss",
"Id": 1234,
"P2": {
"P1": "cccc"
"P3": [
"P1": "aaa"

How can i find all
's value without it iterating all json?

can be anywhere in json.

If no method can do this, can you tell me how to iterate the json?

Answer Source

My approach to this problem would be different.

As JSON doesn't allow depth first search, so convert the json to a Python Object, feed it to an XML decoder and then extract the Node you are intending to search

from xml.dom.minidom import parseString
import json        
def bar(somejson, key):
    def val(node):
        # Searches for the next Element Node containing Value
        e = node.nextSibling
        while e and e.nodeType != e.ELEMENT_NODE:
            e = e.nextSibling
        return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e 
                else None)
    # parse the JSON as XML
    foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),)))
    # and then search all the name tags which are P1's
    # and use the val user function to get the value
    return [val(node) for node in foo_dom.getElementsByTagName('name') 
            if node.firstChild.nodeValue in key]

bar(foo, 'P1')
[u'cccc', u'aaa', u'ss']
bar(foo, ('P1','P2'))
[u'cccc', u'cccc', u'aaa', u'ss']