graphene icon indicating copy to clipboard operation
graphene copied to clipboard

Allow setting a default JSON Encoder and JSON Decoder

Open jtratner opened this issue 4 years ago • 1 comments

Is your feature request related to a problem? Please describe. I'm using graphene_django, which auto-converts model fields to JSONString, which doesn't allow customizing the JSONEncoder class. I'm doing this for some semi-hacky code where I just want to store a big blob-o-stuff, using a custom encoder to convert enums and datetimes.

PS - I'm happy to implement this! Just looking for feedback on what are reasonable modifications to API for this (if any) or if I should give up on this thread :)

Describe the solution you'd like Allow me to specify a custom JSON encoder via some setting or a global.

Describe alternatives you've considered

  1. In my ideal world, I'd be able to pass custom encoders to specific JSON fields. (realistically, you can always merge all the JSONEncoders, so being able to specify just one is fine).
  2. serialize() no longer a static method (seems like overkill for small change)
  3. Make graphene-django create custom JSONString fields based upon jsonencoder / decoder (possible, slightly more goofy perhaps)

Additional context

jtratner avatar Apr 12 '21 04:04 jtratner

I was running into a similar issue with the common TypeError: Object of type datetime is not JSON serializable error.

Currently, I deal with it by creating a Custom Scalar:

# subclass JSONEncoder
class DateTimeEncoder(JSONEncoder):
    """
    Reference --> https://pynative.com/python-serialize-datetime-into-json/
    """
    #Override the default method
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()


class CustomJSONString(graphene.JSONString):
    """
    Allows use of a JSON String for input / output from the GraphQL schema.
    Use of this type is *not recommended* as you lose the benefits of having a defined, static
    schema (one of the key benefits of GraphQL).
    """

    @staticmethod
    def serialize(dt):
        return json.dumps(dt, cls=DateTimeEncoder)

I am not using graphene_django so please ignore if this is not relevant.

opensean avatar May 13 '21 13:05 opensean