Skip to content

Commit

Permalink
Fix root key loss
Browse files Browse the repository at this point in the history
Closes #51
  • Loading branch information
getaarond committed Jan 23, 2020
1 parent 2a114b6 commit 708902f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 3 additions & 1 deletion flatten_json/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,9 @@ def _unflatten(dic, keys, value):
list_keys = sorted(flat_dict.keys())
for i, item in enumerate(list_keys):
if i != len(list_keys) - 1:
if not list_keys[i + 1].startswith(list_keys[i]):
split_key = item.split(separator)
next_split_key = list_keys[i + 1].split(separator)
if not split_key == next_split_key[:-1]:
_unflatten(unflattened_dict, item.split(separator),
flat_dict[item])
else:
Expand Down
16 changes: 16 additions & 0 deletions test_flatten.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,22 @@ def test_unflatten_with_df_issue40(self):
actual = unflatten(dic, '.')
self.assertEqual(actual, expected)

def test_unflatten_with_key_loss_issue51(self):
"""https://github.com/amirziai/flatten/issues/51"""
dic = {
'a': 1,
'a_b': 2,
'a_c.d': 3,
'a_c.e': 4
}
expected = {
'a': 1,
'a_b': 2,
'a_c': {'d': 3, 'e': 4}
}
actual = unflatten(dic, '.')
self.assertEqual(actual, expected)

def test_flatten_preserve_lists_issue43_nested(self):
"""https://github.com/amirziai/flatten/issues/43"""
dic = {
Expand Down

0 comments on commit 708902f

Please sign in to comment.