Parse An Entire Json Object Looking For A Key In Python
I am trying to find if a certain key is in a json object. I create the json with googleRequest = json.loads(googleRequest.content) # its a google api call The json is not always
Solution 1:
You can use a nested function with looping over your dictionary
items and check the type of values each time , if the type was list
or dict
you call the function again else you append the key to list of your total keys :
def find_key(dic):
keys=[]
if isinstance(dic,dict):
for key,value in dic.items():
if isinstance(value,dict):
keys.append(key)
keys.append(find_key(value))
elif isinstance(value,list):
keys.append(key)
keys.append(find_key(value[0]))
else:
keys.append(key)
return keys
result :
['totalItems', 'items', ['kind', 'etag', 'volumeInfo', ['publisher', 'publishedDate', 'authors', None, 'description', 'title'], 'id', 'selfLink'], 'kind']
Solution 2:
Build a function that iterates over the JSON object, recursively:
- If the key is in the current level, return its value.
- If not, run the function for all inner dictionaries.
Solution 3:
"title":\s*"([^"]+)"
Try using re
is other things dont work.See demo.
http://regex101.com/r/lZ5mN8/3
import re
p = re.compile(ur'"title":\s*"([^"]+)"')
test_str = u"{\n \"kind\": \"books#volumes\",\n\"totalItems\": 1,\n\"items\": [\n {\n\"kind\": \"books#volume\",\n\"id\": \"HDvHjwEACAAJ\",\n\"etag\": \"+2K7d2N2VNg\",\n\"selfLink\": \"https://www.googleapis.com/books/v1/volumes/HDvHjwEACAAJ\",\n\"volumeInfo\": {\n\"title\": \"Fahrenheit 451\",\n\"authors\": [\n\"Ray Bradbury\"\n ],\n\"publisher\": \"Voyager\",\n\"publishedDate\": \"2013\",\n\"description\": \"The terrifyingly prophetic novel of a post-literate future Guy Montag is a fireman. His job is to destroy the most illegal of commodities, the source of all discord and unhappiness, the printed book.\",\n\n\n\n\n\n <div style=\"padding-left:2em;\">\n • Location: \n\n Northern Virginia, ☎ 202-210-5936\n\n </div>\n\n\n\n\n <div style=\"padding-left:2em;\"><br />• Post ID: 1234567 washingtondc</div>\n\n\n <div id=\"OtherAdsByThisUser\" data-oid=\"7654321\">"
re.findall(p, test_str)
Solution 4:
for python 3
# python 3 onlydeffind_values_from_key(key, json_object):
ifisinstance(json_object, list):
for list_element in json_object:
yieldfrom find_values_from_key(key, list_element)
elifisinstance(json_object, dict):
if key in json_object:
yield json_object[key]
for dict_value in json_object.values():
yieldfrom find_values_from_key(key, dict_value)
for python 2
# python 2 onlydeffind_values_from_key(key, json_object):
ifisinstance(json_object, list):
for list_element in json_object:
for res in find_values_from_key(key, list_element):
yield res
elifisinstance(json_object, dict):
if key in json_object:
yield json_object[key]
for dict_value in json_object.values():
for res in find_values_from_key(key, dict_value):
yield res
Post a Comment for "Parse An Entire Json Object Looking For A Key In Python"