Search code examples
pythonpython-3.xflaskflask-restful

Cannot convert json


I'm trying to convert flask request to json

from flask import request
import json

req_data = request.get_json(force=True)
json_data = json.dumps(req_data)
json.loads(json_data)

But when I try this I have :

TypeError: Object of type set is not JSON serializable

Can you explain me ?


Solution

  • By default the json.dumps serialize obj to a JSON formatted str using conversion table

    To extend this to recognize other objects, subclass json.JSONEncoder class and implement a default() method with another method that returns a serializable object for o if possible.

    >>> import json
    >>>
    >>> class SetEncoder(json.JSONEncoder):
    ...     def default(self, o):
    ...             if isinstance(o, set):
    ...                     # Do your serailzation here...
    ...             return json.JSONEncoder.default(self, o)
    

    Then you could do json.dumps(obj, cls=SetEncoder).

    For example,

    >>> import json
    >>> my_obj = {1: {1,2, 3}}
    >>>
    >>> class SetEncoder(json.JSONEncoder):
    ...     def default(self, o):
    ...         if isinstance(o, set):
    ...             return list(o)
    ...         return json.JSONEncoder.default(self, o)
    ...
    >>> print(json.dumps(my_obj, cls=SetEncoder))
    {"1": [1, 2, 3]}