Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Last active November 3, 2016 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclipselu/69d07fb265d2e1444a185cdee3682ce3 to your computer and use it in GitHub Desktop.
Save eclipselu/69d07fb265d2e1444a185cdee3682ce3 to your computer and use it in GitHub Desktop.
#!/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