Python json.JSONEncoder.default() Examples

The following are 30 code examples of json.JSONEncoder.default(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module json.JSONEncoder , or try the search function .
Example #1
Source File: transcoding_v1.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encoderpolicy(arg=None):
    """
    Decorator for encoder policy.

    Allows default behaviour to be built up from methods
    registered for different types of things, rather than
    chain of isinstance() calls in a long if-else block.
    """

    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            obj = kwargs.get("obj") or args[-1]
            return wrapped.dispatch(type(obj))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    assert isfunction(arg), arg
    return _mutator(arg) 
Example #2
Source File: json_utils.py    From cloud-inquisitor with Apache License 2.0 6 votes vote down vote up
def default(self, obj):
        """Default object encoder function

        Args:
            obj (:obj:`Any`): Object to be serialized

        Returns:
            JSON string
        """
        if isinstance(obj, datetime):
            return obj.isoformat()

        if issubclass(obj.__class__, Enum.__class__):
            return obj.value

        to_json = getattr(obj, 'to_json', None)
        if to_json:
            out = obj.to_json()
            if issubclass(obj.__class__, Model):
                out.update({'__type': obj.__class__.__name__})

            return out

        return JSONEncoder.default(self, obj) 
Example #3
Source File: __init__.py    From lacquer with Apache License 2.0 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, QuerySpecification):
            keys = ("select", "from_", "where", "group_by", "having", "order_by", "limit")
            ret = OrderedDict([(key, getattr(obj, key)) for key in keys if getattr(obj, key)])
            return ret

        if isinstance(obj, (Node, JoinCriteria)):
            keys = [key for key in obj.__dict__.keys() if
                    key[0] != '_' and key not in ('line', 'pos')]
            ret = {key: getattr(obj, key) for key in keys if getattr(obj, key)}
            return ret

        if isinstance(obj, QualifiedName):
            return obj.parts

        return JSONEncoder.default(self, obj) 
Example #4
Source File: jsonify.py    From st2 with Apache License 2.0 5 votes vote down vote up
def default(self, obj):  # pylint: disable=method-hidden
        if hasattr(obj, '__json__') and six.callable(obj.__json__):
            return obj.__json__()
        else:
            return JSONEncoder.default(self, obj) 
Example #5
Source File: abstractcti.py    From argos with GNU General Public License v3.0 5 votes vote down vote up
def _refreshNodeFromTarget(self):
        """ Refreshes the configuration from the target it monitors (if present).
            The default implementation does nothing; subclasses can override it.
            During updateTarget's execution refreshFromTarget is blocked to avoid loops.
            Typically called from inspector.drawTarget
        """
        pass 
Example #6
Source File: abstractcti.py    From argos with GNU General Public License v3.0 5 votes vote down vote up
def _updateTargetFromNode(self):
        """ Applies the configuration to the target it monitors (if present).
            The default implementation does nothing; subclasses can override it.
            During updateTarget's execution refreshFromTarget is blocked to avoid loops.
        """
        pass



    #################
    # serialization #
    ################# 
Example #7
Source File: abstractcti.py    From argos with GNU General Public License v3.0 5 votes vote down vote up
def resetEditorValue(self, checked=False):
        """ Resets the editor to the default value. Also resets the children.
        """
        # Block all signals to prevent duplicate inspector updates.
        # No need to restore, the editors will be deleted after the reset.
        for subEditor in self._subEditors:
            subEditor.blockSignals(True)

        self.cti.resetToDefault(resetChildren=True)
        # This will commit the children as well.
        self.setData(self.cti.defaultData)
        self.commitAndClose() 
Example #8
Source File: filter.py    From eliot with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()
        return JSONEncoder.default(self, o) 
Example #9
Source File: logclient_operator.py    From aliyun-log-python-sdk with MIT License 5 votes vote down vote up
def get_encoder_cls(encodings):
    class NonUtf8Encoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, six.binary_type):
                for encoding in encodings:
                    try:
                        return obj.decode(encoding)
                    except UnicodeDecodeError as ex:
                        pass
                return obj.decode('utf8', "ignore")

            return JSONEncoder.default(self, obj)

    return NonUtf8Encoder 
Example #10
Source File: doc_output.py    From tri.table with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        if obj is q_MISSING:
            return '<MISSING>'

        return JSONEncoder.default(self, obj) 
Example #11
Source File: model.py    From crom with Apache License 2.0 5 votes vote down vote up
def default(self, o):
		if isinstance(o, BaseResource):
			# print("Saw %r" % o)
			return o._minToJSON()
		else:
			return JSONEncoder.default(self, o) 
Example #12
Source File: make_json_serializable.py    From alexafsm with Apache License 2.0 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj) 
Example #13
Source File: serialization_utils.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, pd.Timestamp):
            return obj.strftime(DATE_TIME_FORMAT)

        # Let the base class default method raise the TypeError
        return JSONEncoder.default(self, obj) 
Example #14
Source File: utils.py    From incubator-ariatosca with Apache License 2.0 5 votes vote down vote up
def default(self, o):  # pylint: disable=method-hidden
        try:
            if hasattr(o, 'value'):
                dict_to_return = o.to_dict(fields=('value',))
                return dict_to_return['value']
            else:
                return o.to_dict()
        except AttributeError:
            return JSONEncoder.default(self, o) 
Example #15
Source File: modelSerializer.py    From graphql-over-kafka with MIT License 5 votes vote down vote up
def default(self, obj):
        try:
            # use the custom json handler
            return obj._json()

        # if the custom json handler doesn't exist
        except AttributeError:
            # perform the normal behavior
            return JSONEncoder.default(self, obj) 
Example #16
Source File: views.py    From 2buntu-blog with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        """
        Encode the provided object.
        """
        if type(o) is QuerySet:
            return list(o)
        elif type(o) is Article:
            return self._encode_article(o)
        elif type(o) is Category:
            return self._encode_category(o)
        elif type(o) is Profile:
            return self._encode_profile(o)
        else:
            return JSONEncoder.default(self, o) 
Example #17
Source File: abstractcti.py    From argos with GNU General Public License v3.0 5 votes vote down vote up
def resetToDefault(self, resetChildren=True):
        """ Resets the data to the default data. By default the children will be reset as well
        """
        self.data = self.defaultData
        if resetChildren:
            for child in self.childItems:
                child.resetToDefault(resetChildren=True) 
Example #18
Source File: utils.py    From CTFsubmitter with GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            encoded = obj.strftime("%b %d %y - %H:%M:%S")
        elif isinstance(obj, ObjectId):
            encoded = str(obj)
        else:
            encoded = JSONEncoder.default(self, obj)
        return encoded 
Example #19
Source File: __init__.py    From openscoring-python with GNU Affero General Public License v3.0 5 votes vote down vote up
def default(self, request):
		if isinstance(request, SimpleRequest):
			return request.__dict__
		else:
			return JSONEncoder.default(self, request) 
Example #20
Source File: internals.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example #21
Source File: internals.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example #22
Source File: internals.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example #23
Source File: jsonify.py    From pecan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def jsonify(obj):
    return _default.default(obj) 
Example #24
Source File: jsonify.py    From pecan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        return jsonify(obj) 
Example #25
Source File: internals.py    From vscode-extension-splunk with MIT License 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example #26
Source File: kellogs.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def _encoder_factory(self, namespace_public_id, expand, is_n1=False):
        class InternalEncoder(JSONEncoder):

            def default(self, obj):
                custom_representation = encode(obj,
                                               namespace_public_id,
                                               expand=expand, is_n1=is_n1)
                if custom_representation is not None:
                    return custom_representation
                # Let the base class default method raise the TypeError
                return JSONEncoder.default(self, obj)
        return InternalEncoder 
Example #27
Source File: __init__.py    From giraffez with Apache License 2.0 5 votes vote down vote up
def _default(self, obj):
    return getattr(obj.__class__, "__json__", _default.default)(obj) 
Example #28
Source File: internals.py    From SplunkAdmins with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example #29
Source File: internals.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o) 
Example #30
Source File: internals.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def default(self, o):
        return o.__dict__ if isinstance(o, ObjectView) else JSONEncoder.default(self, o)