Python json.JSONEncoder() Examples

The following are 30 code examples of json.JSONEncoder(). 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 , or try the search function .
Example #1
Source File: json_combiner.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def save_result(dest_fp):
    """
        Handy function to encode result_json to json and save to file
    """
    with open(dest_fp, 'w') as output_stream:
        rawJSON = \
            json.JSONEncoder(sort_keys=True, indent=4).encode(result_json)
        output_stream.write(rawJSON) 
Example #2
Source File: plotting.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def default(self, obj):
        '''
        Convert objects unrecognized by the default encoder

        Parameters
        ----------
        obj : any
           Arbitrary object to convert

        Returns
        -------
        any
           Python object that JSON encoder will recognize

        '''
        if isinstance(obj, (float, np.float64)):
            return float(obj)
        if isinstance(obj, (long, np.int64)):
            return long(obj)
        if isinstance(obj, (int, np.int32)):
            return int(obj)
        return json.JSONEncoder.default(self, obj) 
Example #3
Source File: decorators.py    From certidude with MIT License 6 votes vote down vote up
def default(self, obj):
        from certidude.user import User
        if isinstance(obj, ipaddress._IPAddressBase):
            return str(obj)
        if isinstance(obj, set):
            return tuple(obj)
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
        if isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        if isinstance(obj, timedelta):
            return obj.total_seconds()
        if isinstance(obj, types.GeneratorType):
            return tuple(obj)
        if isinstance(obj, User):
            return dict(name=obj.name, given_name=obj.given_name,
                surname=obj.surname, mail=obj.mail)
        return json.JSONEncoder.default(self, obj) 
Example #4
Source File: main.py    From twitterscraper with MIT License 6 votes vote down vote up
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        elif isinstance(obj, collections.Iterable):
            return list(obj)
        elif isinstance(obj, dt.datetime):
            return obj.isoformat()
        elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):
            return dict(obj)
        elif hasattr(obj, '__dict__'):
            return {member: getattr(obj, member)
                    for member in dir(obj)
                    if not member.startswith('_') and
                    not hasattr(getattr(obj, member), '__call__')}

        return json.JSONEncoder.default(self, obj) 
Example #5
Source File: runner.py    From NiaPy with MIT License 6 votes vote down vote up
def __export_to_json(self):
        r"""Export the results in the JSON form.

        See Also:
                * :func:`NiaPy.Runner.__createExportDir`

        """

        self.__create_export_dir()

        class NumpyEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, ndarray):
                    return obj.tolist()
                return json.JSONEncoder.default(self, obj)

        dumped = json.dumps(self.results, cls=NumpyEncoder)

        with open(self.__generate_export_name("json"), "w") as outFile:
            json.dump(dumped, outFile)
            logger.info("Export to JSON completed!") 
Example #6
Source File: __init__.py    From quart with MIT License 6 votes vote down vote up
def dumps(object_: Any, app: Optional["Quart"] = None, **kwargs: Any) -> str:
    json_encoder: Type[json.JSONEncoder] = JSONEncoder
    if app is None and _app_ctx_stack.top is not None:  # has_app_context requires a circular import
        app = current_app._get_current_object()

    if app is not None:
        json_encoder = app.json_encoder
        if _request_ctx_stack.top is not None:  # has_request_context requires a circular import
            blueprint = app.blueprints.get(request.blueprint)
            if blueprint is not None and blueprint.json_encoder is not None:
                json_encoder = blueprint.json_encoder
        kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])
        kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])
    kwargs.setdefault("sort_keys", True)
    kwargs.setdefault("cls", json_encoder)

    return json.dumps(object_, **kwargs) 
Example #7
Source File: json_utils.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def default(self, o):  # pylint: disable=method-hidden
    if isinstance(o, datetime.datetime):
      return {
          '__type__': 'datetime',
          'year': o.year,
          'month': o.month,
          'day': o.day,
          'hour': o.hour,
          'minute': o.minute,
          'second': o.second,
          'microsecond': o.microsecond,
      }
    if isinstance(o, datetime.date):
      return {
          '__type__': 'date',
          'year': o.year,
          'month': o.month,
          'day': o.day,
      }

    return json.JSONEncoder.default(self, o) 
Example #8
Source File: serialization.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, obj: Any) -> Any:
        try:
            return pydantic_encoder(obj)
        except TypeError:
            pass

        if isinstance(obj, np.ndarray):
            if obj.shape:
                data = {"_nd_": True, "dtype": obj.dtype.str, "data": np.ascontiguousarray(obj).tobytes().hex()}
                if len(obj.shape) > 1:
                    data["shape"] = obj.shape
                return data

            else:
                # Converts np.array(5) -> 5
                return obj.tolist()

        return json.JSONEncoder.default(self, obj) 
Example #9
Source File: atffile.py    From pyoracc with GNU General Public License v3.0 6 votes vote down vote up
def to_json(self, skip_empty=True, **kwargs):
        '''Return a JSON representation of the parsed file.

        The optional skip_empty argument determines whether keys
        with empty values are included in the output. Set it to
        False to see all possible object members.

        Otherwise it accepts the same optional arguments as
        json.dumps().'''
        def _make_serializable(obj):
            '''Construct a dict representation of an object.

            This is necessary to handle our custom objects
            which json.JSONEncoder doesn't know how to
            serialize.'''

            return {k: v
                    for k, v in vars(obj).items()
                    if not str(k).startswith('_') and not (
                        skip_empty and not v and not isinstance(v, Number)
                    )}

        kwargs.setdefault('indent', 2)
        kwargs.setdefault('default', _make_serializable)
        return json.dumps(self.text, **kwargs) 
Example #10
Source File: __init__.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        from decimal import Decimal
        from datetime import datetime
        if isinstance(obj, Decimal):
            return float(obj)
        if isinstance(obj, datetime):
            return str(obj)

        return json.JSONEncoder.default(self, obj) 
Example #11
Source File: base_handler.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def default(self, obj):  # pylint: disable=arguments-differ,method-hidden
    if isinstance(obj, ndb.Model):
      dict_obj = obj.to_dict()
      dict_obj['id'] = obj.key.id()
      return dict_obj
    if isinstance(obj, datetime.datetime):
      return int((obj - self._EPOCH).total_seconds())
    if hasattr(obj, 'to_dict'):
      return obj.to_dict()
    if isinstance(obj, cgi.FieldStorage):
      return str(obj)
    if isinstance(obj, bytes):
      return obj.decode('utf-8')

    return json.JSONEncoder.default(self, obj) 
Example #12
Source File: encoding.py    From awe with MIT License 5 votes vote down vote up
def default(self, o):
        for cls, serializer in self.serializers.items():
            if isinstance(o, cls):
                return serializer(o)
        return super(JSONEncoder, self).default(o) 
Example #13
Source File: api.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, models.SendJob):
            return self._encode_send_job(o)
        if isinstance(o, models.RemindJob):
            return self._encode_remind_job(o)
        if isinstance(o, models.DisabledReply):
            return self._encode_disabled_reply(o)
        if isinstance(o, models.Snippet):
            return self._encode_snippet(o)
        if isinstance(o, datetime.datetime):
            return o.replace(tzinfo=UTC).isoformat()
        if isinstance(o, datetime.date):
            return o.isoformat()
        return json.JSONEncoder.default(self, o) 
Example #14
Source File: encoding.py    From awe with MIT License 5 votes vote down vote up
def __init__(self, serializers):
        super(JSONEncoder, self).__init__(separators=(',', ':'))
        self.serializers = serializers 
Example #15
Source File: json_utils.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def dumps(obj, *args, **kwargs):
  """Custom json.dumps using custom encoder JSONEncoder defined in this file."""
  kwargs['cls'] = JSONEncoder
  kwargs['sort_keys'] = True
  return json.dumps(obj, *args, **kwargs) 
Example #16
Source File: example_mqtt.py    From PyZwaver with GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, set):
            return list(set)
        elif isinstance(obj, bytes):
            return "".join(map(chr, obj))
        return json.JSONEncoder.default(self, obj) 
Example #17
Source File: json.py    From lambda-chef-node-cleanup with Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, 'to_dict'):
            return maybe_call(obj.to_dict)
        elif hasattr(obj, 'to_list'):
            return maybe_call(obj.to_list)
        elif isinstance(obj, types.GeneratorType):
            return list(obj)
        return super(JSONEncoder, self).default(obj) 
Example #18
Source File: CommonMixin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 5 votes vote down vote up
def default(self, obj):  # pylint: disable=W0221,E0202
        """JSON serialization logic for objects not serializable by default json code."""
        toDict = getattr(obj, "toDict", None)
        if (toDict is not None):
            return toDict()

        if isinstance(obj, (datetime, date)):
            return obj.isoformat()

        if (isinstance(obj, REGEX_TYPE)):
            return obj.pattern

        return json.JSONEncoder.default(self, obj) 
Example #19
Source File: skinnedanimation.py    From renpy-shader with MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (KeyFrame, Frame, BoneData, SkinnedAnimation)):
            d = obj.__dict__.copy()
            for ignore in getattr(obj, "jsonIgnore", []):
                if ignore in d:
                    del d[ignore]
            return d
        elif isinstance(obj, euclid.Vector3):
            return (obj.x, obj.y, obj.z)
        elif isinstance(obj, ctypes.Array):
            return list(obj)
        return json.JSONEncoder.default(self, obj) 
Example #20
Source File: skin.py    From renpy-shader with MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, (SkinningBone, SkinnedImage, skinnedmesh.SkinnedMesh)):
            d = obj.__dict__.copy()
            for ignore in JSON_IGNORES + getattr(obj, "jsonIgnore", []):
                if ignore in d:
                    del d[ignore]
            return d
        elif isinstance(obj, euclid.Vector3):
            return (obj.x, obj.y, obj.z)
        elif isinstance(obj, ctypes.Array):
            return list(obj)
        return json.JSONEncoder.default(self, obj) 
Example #21
Source File: resources.py    From panoptes with Apache License 2.0 5 votes vote down vote up
def default(self, o):  # pylint: disable=E0202
        if isinstance(o, set):
            return list(o)
        if isinstance(o, PanoptesResource):
            return o.__dict__[u'_PanoptesResource__data']
        return json.JSONEncoder.default(self, o) 
Example #22
Source File: pygraphistry.py    From pygraphistry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, numpy.ndarray) and obj.ndim == 1:
                return obj.tolist()
        elif isinstance(obj, numpy.generic):
            return obj.item()
        elif isinstance(obj, type(pandas.NaT)):
            return None
        elif isinstance(obj, datetime):
            return obj.isoformat()
        return json.JSONEncoder.default(self, obj) 
Example #23
Source File: app.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def __init__(self, app, extra_environ=None, relative_to=None,
                 use_unicode=True, cookiejar=None, parser_features=None,
                 json_encoder=None, lint=True):
        if 'WEBTEST_TARGET_URL' in os.environ:
            app = os.environ['WEBTEST_TARGET_URL']
        if isinstance(app, string_types):
            if app.startswith('http'):
                try:
                    from wsgiproxy import HostProxy
                except ImportError:  # pragma: no cover
                    raise ImportError((
                        'Using webtest with a real url requires WSGIProxy2. '
                        'Please install it with: '
                        'pip install WSGIProxy2'))
                if '#' not in app:
                    app += '#httplib'
                url, client = app.split('#', 1)
                app = HostProxy(url, client=client)
            else:
                from paste.deploy import loadapp
                # @@: Should pick up relative_to from calling module's
                # __file__
                app = loadapp(app, relative_to=relative_to)
        self.app = app
        self.lint = lint
        self.relative_to = relative_to
        if extra_environ is None:
            extra_environ = {}
        self.extra_environ = extra_environ
        self.use_unicode = use_unicode
        self.cookiejar = cookiejar or http_cookiejar.CookieJar(
            policy=CookiePolicy())
        if parser_features is None:
            parser_features = 'html.parser'
        self.RequestClass.ResponseClass.parser_features = parser_features
        if json_encoder is None:
            json_encoder = json.JSONEncoder
        self.JSONEncoder = json_encoder 
Example #24
Source File: crawlstats.py    From cc-crawl-statistics with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, MonthlyCrawlSet):
            return o.get_bits()
        if isinstance(o, HyperLogLog):
            return CrawlStatsJSONEncoder.json_encode_hyperloglog(o)
        return json.JSONEncoder.default(self, o) 
Example #25
Source File: index.py    From importmagic with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, SymbolIndex):
            d = o._tree.copy()
            d.update(('.' + name, getattr(o, name))
                     for name in SymbolIndex._SERIALIZED_ATTRIBUTES)
            if o._lib_locations is not None:
                d['.lib_locations'] = o._lib_locations
            return d
        return super(JSONEncoder, self).default(o) 
Example #26
Source File: json.py    From numcodecs with MIT License 5 votes vote down vote up
def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True,
                 check_circular=True, allow_nan=True, sort_keys=True, indent=None,
                 separators=None, strict=True):
        self._text_encoding = encoding
        if separators is None:
            # ensure separators are explicitly specified, and consistent behaviour across
            # Python versions, and most compact representation if indent is None
            if indent is None:
                separators = ',', ':'
            else:
                separators = ', ', ': '
        separators = tuple(separators)
        self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
                                    check_circular=check_circular, allow_nan=allow_nan,
                                    indent=indent, separators=separators,
                                    sort_keys=sort_keys)
        self._encoder = _json.JSONEncoder(**self._encoder_config)
        self._decoder_config = dict(strict=strict)
        self._decoder = _json.JSONDecoder(**self._decoder_config) 
Example #27
Source File: index.py    From importmagic with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def serialize(self, fd=None):
        if fd is None:
            return json.dumps(self, cls=JSONEncoder)
        return json.dump(self, fd, cls=JSONEncoder) 
Example #28
Source File: ClassAverages.py    From 3D-BoundingBox with MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self,obj) 
Example #29
Source File: metrics.py    From panoptes with Apache License 2.0 5 votes vote down vote up
def default(self, o):  # pylint: disable=E0202
        if isinstance(o, set):
            return list(o)
        if isinstance(o, PanoptesResource):
            return o.__dict__[u'_PanoptesResource__data']
        if isinstance(o, PanoptesMetric):
            return o.__dict__[u'_PanoptesMetric__data']
        if isinstance(o, PanoptesMetricDimension):
            return o.__dict__[u'_PanoptesMetricDimension__data']
        return json.JSONEncoder.default(self, o) 
Example #30
Source File: enrichment.py    From panoptes with Apache License 2.0 5 votes vote down vote up
def default(self, o):  # pylint: disable=E0202
        if isinstance(o, set):
            return list(o)
        if isinstance(o, PanoptesResource):
            return o.__dict__[u'_PanoptesResource__data']
        if isinstance(o, PanoptesEnrichmentSet):
            return o.__dict__[u'_PanoptesEnrichmentSet__data']
        if isinstance(o, PanoptesEnrichmentGroup):
            return o.__dict__[u'_PanoptesEnrichmentGroup__data']
        if isinstance(o, PanoptesEnrichmentGroupSet):
            return o.__dict__[u'_PanoptesEnrichmentGroupSet__data']
        if isinstance(o, PanoptesEnrichmentMultiGroupSet):
            return o.__dict__[u'_PanoptesEnrichmentMultiGroupSet__data']
        return json.JSONEncoder.default(self, o)