How to find a particular json value by key?

前端 未结 8 1837
再見小時候
再見小時候 2020-11-29 04:23

There is a json like this:

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


        
8条回答
  •  一整个雨季
    2020-11-29 04:37

    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']
    

提交回复
热议问题