Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix data loss when a root key contains another root key #52

Merged
merged 1 commit into from
Jan 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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