Generator to get value of key from any dictionary(json)

This will return list of value that matches to key we provided. This will accept only json/dict, if not then need to json.loads(str) to make dict.


def search_value_from_json(json_str="This could be a json/dict", search_key="what to search from given json/dict"):
if search_key in json_str:
yield json_str[search_key]
for key in json_str:
if isinstance(json_str[key], dict):
for searched_key in search_value_from_json(json_str[key],search_key):
yield searched_key

elif isinstance(json_str[key], list):
for item in json_str[key]:
for searched_key in search_value_from_json(item,search_key):
yield searched_key

USAGES:
list_value = list(search_value_from_json(json_str, key_to_find))

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: