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

In the spirit of default= parameter, a similar default_key= parameter #156

Open
kcrossen opened this issue Jan 26, 2017 · 2 comments
Open

Comments

@kcrossen
Copy link

In the spirit of the dump/dumps default= parameter, a similar default_key= could be specified for
def _stringify_key(key):

For example, currently one may conveniently support UTC datetime as a dictionary value by:

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime.datetime):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")

but _stringify_key fails when datetime is a dictionary key.

All of the same cautions would apply, of course, but at least someone who thought they knew what they were doing could get hurt their own way.

I hacked it w/

        elif _use_decimal and isinstance(key, Decimal):
            key = str(key)
        # kcrossen ...
        elif isinstance(key, datetime.datetime):
            key = key.isoformat()
        # ... kcrossen
        elif _skipkeys:
            key = None
        else:
            raise TypeError("key " + repr(key) + " is not a string")
        return key

but it doesn't feel righteous somehow.

@DeoLeung
Copy link

DeoLeung commented Dec 5, 2017

it will be great that we could provide customer parser to turn non-string keys into str, like numpy.int64 which is failing now

@kcrossen
Copy link
Author

kcrossen commented Dec 5, 2017

Can also be done to allow OrderedDict to remain ordered while usual dict is sorted:

        if (_item_sort_key and 
            # kcrossen ...
            (not isinstance(dct, OrderedDict))):
            # ... kcrossen
            items = []

approximately line 585 in encoder.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants