There is a json like this:
{
\"P1\": \"ss\",
\"Id\": 1234,
\"P2\": {
\"P1\": \"cccc\"
},
\"P3\": [
{
\"P1\": \"aaa\"
}
I don't think there's any way of finding all values associated with P1 without iterating over the whole structure. Here's a recursive way to do it that first deserializes the json object in a file into an equivalent Python object. To simplify things most of the work is done via a private nested function.
def find_values(id, obj):
results = []
def _find_values(id, obj):
try:
for key, value in obj.iteritems():
if key == id:
results.append(value)
elif not isinstance(value, basestring):
_find_values(id, value)
except AttributeError:
pass
try:
for item in obj:
if not isinstance(item, basestring):
_find_values(id, item)
except TypeError:
pass
if not isinstance(obj, basestring):
_find_values(id, obj)
return results
import json
with open('data.json') as json_file:
obj = json.load(json_file)
print find_values('P1', obj)
Using json
to convert the json to Python objects and then going through recursively works best. This example does include going through lists.
import json
def get_all(myjson, key):
if type(myjson) == str:
myjson = json.loads(myjson)
if type(myjson) is dict:
for jsonkey in myjson:
if type(myjson[jsonkey]) in (list, dict):
get_all(myjson[jsonkey], key)
elif jsonkey == key:
print myjson[jsonkey]
elif type(myjson) is list:
for item in myjson:
if type(item) in (list, dict):
get_all(item, key)