There is a JSON like this:

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

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

P.S.: P1 can be anywhere in the 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

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相关问答推荐

Bash和echo命令出现意外结果

如何在JQ过滤器文件中使用多行?

数据到jsonObject到数据到 struct 是可能的吗?

Nifi - 忽略(或删除)JSON 的第一个数字

是否可以在有条件的情况下将 json 对象转换为 JOLT 中的数组?

如何从条带订阅响应对象中正确获取 struct 项?

从 JSON 对象中删除键值对

如何将任意 json 对象发布到 webapi

从 Postgres 中的 json 对象中提取键、值

哪个更好:Json 或 XML (PHP)

在 bash 中将 CSV 转换为 JSON

如何使用 Jackson 定义可选的 json 字段

通过 RestAssured 中的 JsonPath 访问匿名数组的元素

gson:将 null 视为空字符串

如何将有向无环图 (DAG) 存储为 JSON?

PostgreSQL 中的 JSON 模式验证?

在 JSON.NET 中序列化派生类时的字段顺序

YAML 将 5e-6 加载为字符串而不是数字

如何对 jq 中的 map 数组中的值求和?

ASP.NET Web API JSON 输出中没有时间的日期