Created
April 14, 2016 16:31
-
-
Save ptrourke/89fed54ab053974bad9f6e07ca22ca2d to your computer and use it in GitHub Desktop.
Prints all values from one subkey of a json file of a specific format if it includes a particular substring (used e.g. for extracting values from a json manifest)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'ptrourke' | |
import json | |
""" | |
Print value from one subkey `key2` in a json file of the structure below | |
if it includes a substring `filter_string` | |
'key': { | |
'key2': ['value1sstring', 'value2', 'value3sstring'], | |
# [...] | |
} | |
prints | |
'key: value1sstring, value3sstring' | |
""" | |
json_file_name = '/home/ptrourke/workspace/projectone/collections/manifest.json' | |
key2 = 'aka' | |
filter_string = 'lccn.loc.gov' | |
with open(json_file_name) as manifest_json: | |
manifest = json.load(manifest_json) | |
sections = [] | |
for key in manifest: | |
key2_values = manifest[key].get(key2,[]) | |
filter_matches = [] | |
for key2_value in key2_values: | |
if filter_string in key2_value: | |
filter_matches.append(key2_value) | |
sections.append('%s: %s' % (key, ','.join(filter_matches))) | |
sections = sorted(sections) | |
for section_item in sections: | |
print(section_item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment