Last active
August 29, 2015 14:12
-
-
Save tusbar/2e5d7c805338acd2412f to your computer and use it in GitHub Desktop.
json2kvp
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
import json | |
def build_dict_prefix(current, new): | |
if current: | |
return '{}.{}'.format(current, new) | |
return new | |
def build_list_prefix(current, index): | |
if current: | |
return '{}[{}]'.format(current, index) | |
return '[{}]'.format(index) | |
def object_to_kvp(obj, prefix=None): | |
if isinstance(obj, dict): | |
for k, v in obj.iteritems(): | |
for kvp in object_to_kvp(v, prefix=build_dict_prefix(prefix, k)): | |
yield kvp | |
elif isinstance(obj, list): | |
for i, v in enumerate(obj): | |
for kvp in object_to_kvp(v, prefix=build_list_prefix(prefix, i)): | |
yield kvp | |
else: | |
yield prefix, obj | |
def print_json_to_kvp(string): | |
obj = json.loads(string) | |
for k, v in object_to_kvp(obj): | |
if k: | |
print '{}={}'.format(k, v) | |
else: | |
print v |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment