As I said in my other answer, I don’t think there is a way of finding all values associated with the "P1"
key without iterating over the whole structure. However I’ve come up with even better way to do that which came to me while looking at @Mike Brennan’s answer to another JSON-related question How to get string objects instead of Unicode from JSON?
The basic idea is to use the object_hook
parameter that json.loads()
accepts just to watch what is being decoded and check for the sought-after value.
Note: This will only work if the representation is of a JSON object
(i.e. something enclosed in curly braces {}
), as in your sample.
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) output:
['cccc', 'aaa', 'ss']