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

查看:27
本文介绍了如何按键查找特定的 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?

P.S.:P1 可以是 JSON 中的任何地方.

P.S.: P1 can be anywhere in the 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 解码器,然后提取您要搜索的节点

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天全站免登陆