python - 如何按键查找特定的 JSON 值?

标签 python json search

有一个这样的JSON:

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

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

P.S.:P1 可以是 JSON 中的 anywhere

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

最佳答案

正如我在 other answer 中所说的那样,我认为没有一种方法可以在不遍历整个结构的情况下找到与 "P1" 键关联的所有值。但是,我在查看@Mike Brennan 的answer 时想到了更好的方法来做这件事。到另一个与 JSON 相关的问题 How to get string objects instead of Unicode from JSON?

基本思想是使用object_hook参数json.loads()接受只是为了观看正在解码的内容并检查抢手的值。

注意:这仅在表示为 JSON object 时才有效(即包含在 curly braces {} 中的内容),如您的示例中所示。

from __future__ import print_function
import json

def find_values(id, json_repr):
    results = []

    def _decode_dict(a_dict):
        try:
            results.append(a_dict[id])
        except KeyError:
            pass
        return a_dict

    json.loads(json_repr, object_hook=_decode_dict) # Return value ignored.
    return results

json_repr = '{"P1": "ss", "Id": 1234, "P2": {"P1": "cccc"}, "P3": [{"P1": "aaa"}]}'
print(find_values('P1', json_repr))

(Python 3)输出:

['cccc', 'aaa', 'ss']

关于python - 如何按键查找特定的 JSON 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14048948/

相关文章:

mysql - 按标签名称或资源名称搜索资源

python - Pandas 获取部分数据框并对值进行归一化

python - Pandas :用条件替换列中的值

python - 比较python中的字符串以查找错误

java - 如何在json改造的根部使用可变键解析json

json - 如何使用Json4s将Map转Json

php - 在 PHP 中,使用 "LIKE"从 MySQL 搜索结果中获取整个单词

python - 如何在Python中平滑概率分布图?

iphone - RestKit 和核心数据整数数组

search - 解决方案 4.1 java.lang.IllegalArgumentException : first position increment must be > 0 (got 0)