-
-
Save eclipselu/69d07fb265d2e1444a185cdee3682ce3 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# encoding: utf-8 | |
import json | |
def flatten(json_str): | |
dic = json.loads(json_str) | |
flattened_dic = _flatten(dic) | |
return json.dumps(flattened_dic) | |
def _flatten(dic): | |
result = {} | |
for k, v in dic.iteritems(): | |
if not isinstance(v, dict): | |
result[k] = v | |
else: | |
for kk, vv in _flatten(v).iteritems(): | |
result['%s.%s' % (k, kk)] = vv | |
return result | |
print flatten(json.dumps({ | |
'a': 1, | |
'b': 2, | |
'c': { | |
'c1': 'test', | |
'c2': [1, 2, 3] | |
} | |
})) | |
# {"a": 1, "b": 2, "c.c2": [1, 2, 3], "c.c1": "test"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment