Skip to content

Instantly share code, notes, and snippets.

@theorm
Last active December 14, 2015 17:28
Show Gist options
  • Select an option

  • Save theorm/5122207 to your computer and use it in GitHub Desktop.

Select an option

Save theorm/5122207 to your computer and use it in GitHub Desktop.
Convert properties file style dict to JSON style
# -*- 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
test:
PYTHONPATH=. python test_dedot.py
# -*- 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