Last active
December 14, 2015 17:28
-
-
Save theorm/5122207 to your computer and use it in GitHub Desktop.
Convert properties file style dict to JSON style
This file contains hidden or 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
| # -*- coding: utf-8 -*- | |
| def dedot(doc): | |
| '''Convert proprty file style dict to JSON style dict: | |
| { | |
| 'foo.bar' : 1, | |
| 'foo.baz.0' : 'a', | |
| 'foo.baz.1' : 'b', | |
| } | |
| to | |
| { | |
| 'foo' : { | |
| 'bar' : 1 | |
| 'baz' : ['a','b'] | |
| }, | |
| } | |
| ''' | |
| out = {} | |
| for k in sorted(doc.keys()): | |
| parent = None | |
| current = out | |
| prev_key = None | |
| for key in k.split('.'): | |
| try: | |
| int_key = int(key) | |
| if len(current) > 0 and not isinstance(current, list): | |
| raise Exception('Wrong input dict. Expecting list.') | |
| elif isinstance(current, dict): | |
| parent[prev_key] = [] | |
| current = parent[prev_key] | |
| if int_key >= len(current): | |
| current.insert(int_key, {}) | |
| prev_key = int_key | |
| parent = current | |
| current = current[int_key] | |
| except ValueError: | |
| if key not in current: | |
| current[key] = {} | |
| parent = current | |
| current = current[key] | |
| prev_key = key | |
| parent[prev_key] = doc[k] | |
| return out |
This file contains hidden or 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
| test: | |
| PYTHONPATH=. python test_dedot.py |
This file contains hidden or 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
| # -*- coding: utf-8 -*- | |
| from dedot import dedot | |
| def test_dedot(): | |
| doted_dict = { | |
| 'foo.bar' : 1, | |
| 'foo.baz.0' : 'a', | |
| 'foo.baz.1' : 'b', | |
| 'spam.0.eggs' : 10, | |
| 'spam.0.bread' : 20, | |
| } | |
| json_dict = dedot(doted_dict) | |
| assert json_dict == { | |
| 'foo' : { | |
| 'bar' : 1, | |
| 'baz' : ['a', 'b'], | |
| }, | |
| 'spam' : [ | |
| { | |
| 'eggs' : 10, | |
| 'bread' : 20, | |
| } | |
| ] | |
| } | |
| if __name__ == '__main__': | |
| test_dedot() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment