amancevice / flatsplode

Flatten/Explode JSON objects
MIT License
17 stars 7 forks source link

[bug] Proper handling of "falsy" values such as 0, 0.0, "", etc. #2

Closed olegbonar closed 3 years ago

olegbonar commented 3 years ago

The test code

from flatsplode import flatsplode

list(flatsplode(
        {
            "test": [0, 0.0, [], ""]
        }
))

turns out to return:

[{'test': None}, {'test': None}, {'test': None}, {'test': None}]

which is not expected.

The problem line is https://github.com/amancevice/flatsplode/blob/4ff90650d736a23e8b7ac28921465eb8cbb6810a/flatsplode/flatsplode.py#L72 however I'm not yet sure why it's needed.

amancevice commented 3 years ago

Thanks for reporting, I'll look into this

olegbonar commented 3 years ago

A simple fix might look like:

def iterkv(item, parents=(), join='.'):
    """ Iterate over key/values of item recursively.
        :param dict item: Item to flatten
        :param tuple parents: Running tuple of parent keys
    """
    for key, val in item.items():
        path = parents + (key,)     # Assemble path parts
        key = str.join(join, path)  # join path parts

        if isinstance(val, dict) and val:
            yield from iterkv(val, path, join)
        else:                
            yield (key, val)

Then,

list(flatsplode(
        {
            "test": [0, 0.0, [], "", 123]
        }
))

yields

[{'test': 0}, {'test': 0.0}, {'test': []}, {'test': ''}, {'test': 123}]

Would be happy to add a fix if it's ok.

amancevice commented 3 years ago

I tweaked your fix to maintain existing behavior around empty dicts, but thanks for suggesting!

Here's the fix