有一个这样的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/