如何通过键查找特定的json值? [英] How to find a particular json value by key?

查看:373
本文介绍了如何通过键查找特定的json值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个像这样的json:

There is a json like this:

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

如何在不迭代所有json的情况下找到所有P1的值?

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

PS:P1可以在json中的任何位置.

PS:P1 can be anywhere in json.

如果没有方法可以做到这一点,您能告诉我如何遍历json吗?

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

推荐答案

我对这个问题的处理方法会有所不同.

My approach to this problem would be different.

由于JSON不允许深度优先搜索,因此将json转换为Python对象,将其提供给XML解码器,然后提取要搜索的Node

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

这篇关于如何通过键查找特定的json值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆