Skip to content

Iterable support #59

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 3 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 @@ -15,6 +15,7 @@
import copy
import re
from math import isnan
from collections.abc import Iterable


def _construct_key(previous_key, separator, new_key):
Expand Down Expand Up @@ -72,7 +73,7 @@ def _flatten(object_, key):
_flatten(object_[object_key], _construct_key(key,
separator,
object_key))
elif isinstance(object_, (list, set, tuple)):
elif isinstance(object_, Iterable):
for index, item in enumerate(object_):
_flatten(item, _construct_key(key, separator, index))
# Anything left take as is
Expand Down
13 changes: 13 additions & 0 deletions test_flatten.py
Original file line number Diff line number Diff line change
Expand Up @@ -2171,6 +2171,19 @@ def test_flatten_ignore_keys(self):
actual = flatten(dic, root_keys_to_ignore={'b', 'c'})
self.assertEqual(actual, expected)

def test_flatten_custom_iterable(self):
class customIter:
def __init__(self, lst):
self.val = lst

def __iter__(self):
return self.val.__iter__()

elst = {'a': customIter([0, 1, 2])}
expected = {'a_0': 0, 'a_1': 1, 'a_2': 2}
actual = flatten(elst)
self.assertEqual(actual, expected)

def test_command_line(self):
input_stream = StringIO(u'{"a": {"b": 1}}')
output_stream = StringIO()
Expand Down