Skip to content

Same-level elements with common prefix #50

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion flatten_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,8 @@ 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]):
if not list_keys[i + 1].startswith('{}{}'.format(list_keys[i],
separator)):
_unflatten(unflattened_dict, item.split(separator),
flat_dict[item])
else:
Expand Down
10 changes: 10 additions & 0 deletions test_flatten.py
Original file line number Diff line number Diff line change
Expand Up @@ -2156,6 +2156,16 @@ def test_unflatten_with_list_deep(self):
actual = unflatten_list(dic_flatten)
self.assertEqual(actual, dic)

def test_unflatten_with_common_prefixes(self):
dic = {
'a': 1,
'ab': 2,
'abc': 3,
}
dic_flatten = flatten(dic)
actual = unflatten(dic_flatten)
self.assertEqual(actual, dic)

def test_flatten_ignore_keys(self):
"""Ignore a set of root keys for processing"""
dic = {
Expand Down