Python json.JSONEncoder() Examples

The following are 30 code examples for showing how to use json.JSONEncoder(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module json , or try the search function .

Example 1
Project: indras_net   Author: gcallah   File: json_combiner.py    License: 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
Project: QCElemental   Author: MolSSI   File: serialization.py    License: 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 3
Project: quart   Author: pgjones   File: __init__.py    License: 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 4
Project: aws-ops-automator   Author: awslabs   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def default(self, o):
        if types.FunctionType == type(o):
            return o.__name__
        # sets become lists
        if isinstance(o, set):
            return list(o)
        # date times become strings
        if isinstance(o, datetime):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return float(o)
        if isinstance(o, type):
            return str(o)
        if isinstance(o, Exception):
            return str(o)
        if isinstance(o, set):
            return str(o, 'utf-8')
        if isinstance(o, bytes):
            return str(o, 'utf-8')
        
        return json.JSONEncoder.default(self, o) 
Example 5
Project: twitterscraper   Author: taspinar   File: main.py    License: 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 6
Project: certidude   Author: laurivosandi   File: decorators.py    License: 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 7
Project: python-esppy   Author: sassoftware   File: plotting.py    License: 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 8
Project: pyoracc   Author: oracc   File: atffile.py    License: 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 9
Project: numcodecs   Author: zarr-developers   File: json.py    License: MIT License 6 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 10
Project: NiaPy   Author: NiaOrg   File: runner.py    License: 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 11
Project: clusterfuzz   Author: google   File: json_utils.py    License: 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 12
Project: indras_net   Author: gcallah   File: agent.py    License: GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if hasattr(o, 'to_json'):
            return o.to_json()
        elif isinstance(o, np.int64):
            return int(o)
        elif isinstance(o, types.FunctionType):
            return get_func_name(o)  # can't JSON a function!
        else:
            return json.JSONEncoder.default(self, o) 
Example 13
Project: indras_net   Author: gcallah   File: json_combiner.py    License: GNU General Public License v3.0 5 votes vote down vote up
def print_result():
    """
        Handy function to print result_json
    """
    print(json.JSONEncoder(sort_keys=True, indent=4).encode(result_json)) 
Example 14
Project: indras_net   Author: gcallah   File: json_generator.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_json(model_kv):
    """
        Generates json  and prints to stdout
        model_kv is generated by parse_docstring()
        it contains the key value pair of each field
        (dict) -> None
    """
    if(type(model_kv) != dict):
        script_output("generate_json(dict), check function def")
        exit(1)

    print(json.JSONEncoder(sort_keys=True, indent=4).encode(model_kv)) 
Example 15
Project: EDeN   Author: fabriziocosta   File: __init__.py    License: MIT License 5 votes vote down vote up
def default(self, obj):
        """default."""
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj) 
Example 16
Project: everyclass-server   Author: everyclass   File: jsonable.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, JSONSerializable):
            return obj.__json_encode__()
        return json.JSONEncoder.default(self, obj) 
Example 17
Project: gated-graph-transformer-network   Author: hexahedria   File: util.py    License: MIT License 5 votes vote down vote up
def object_hash(thing):
    class EnumEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, enum.Enum):
                return obj.name
            return super().default(obj)
    strform = json.dumps(thing, sort_keys=True, cls=EnumEncoder)
    h = hashlib.sha1()
    h.update(strform.encode('utf-8'))
    return h.hexdigest() 
Example 18
Project: SecPi   Author: SecPi   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.date):
            return obj.isoformat()
        return json.JSONEncoder.default(obj) 
Example 19
Project: QCElemental   Author: MolSSI   File: serialization.py    License: BSD 3-Clause "New" or "Revised" License 5 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:
                return obj.ravel().tolist()
            else:
                return obj.tolist()

        return json.JSONEncoder.default(self, obj) 
Example 20
Project: Paradrop   Author: ParadropLabs   File: chute_api.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, o):
        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            return repr(o) 
Example 21
Project: Paradrop   Author: ParadropLabs   File: chute_api.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, o):
        try:
            return json.JSONEncoder.default(self, o)
        except TypeError:
            return o.__dict__ 
Example 22
Project: aws-ops-automator   Author: awslabs   File: build_task_custom_resource.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, set):
            return list(o)
        if isinstance(o, datetime):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return str(trunc(o))
        if isinstance(o, Exception):
            return str(o)
        return json.JSONEncoder.default(self, o) 
Example 23
Project: CTask   Author: yangmv   File: public.py    License: GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj) 
Example 24
Project: stoq   Author: PUNCH-Cyber   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, o) -> Any:
        if isinstance(o, bytes):
            return UnicodeDammit(o).unicode_markup  # type: ignore
        elif isinstance(o, datetime.datetime):
            return str(o)
        elif isinstance(o, set):
            return list(o)
        try:
            return vars(o)
        except Exception:
            pass
        return json.JSONEncoder.default(self, o) 
Example 25
Project: compare-codecs   Author: google   File: gviz_api.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
    json.JSONEncoder.__init__(self,
                              separators=(",", ":"),
                              ensure_ascii=False) 
Example 26
Project: tekore   Author: felix-hilden   File: serialise.py    License: MIT License 5 votes vote down vote up
def json(self) -> str:
        """
        JSON representation of a model.

        Returns
        -------
        str
            JSON representation
        """
        return JSONEncoder().encode(self) 
Example 27
Project: olympe   Author: Parrot-Developers   File: json.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if issubclass(o.__class__, ArsdkBitfield):
            return "olympe.enums." + o.__class__._feature_name_ + '.' + str(o)
        elif issubclass(o.__class__, ArsdkEnum):
            return 'olympe.enums.' + o.__class__._feature_name_ + '.' + str(o)
        elif issubclass(o.__class__, ArsdkMessage):
            return 'olympe.messages.' + o.feature_name + '.' + str(o)
        return super(JSONEncoder, self).default(o) 
Example 28
Project: lattice   Author: tensorflow   File: premade_test.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, obj):
      if isinstance(obj, np.int32):
        return int(obj)
      if isinstance(obj, np.ndarray):
        return obj.tolist()
      return json.JSONEncoder.default(self, obj) 
Example 29
Project: spotify-tensorflow   Author: spotify   File: example_decoders.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, obj):
            if isinstance(obj, np.ndarray):
                return obj.tolist()
            if isinstance(obj, bytes):
                return obj.decode()
            return json.JSONEncoder.default(self, obj) 
Example 30
Project: datasette   Author: simonw   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, sqlite3.Row):
            return tuple(obj)
        if isinstance(obj, sqlite3.Cursor):
            return list(obj)
        if isinstance(obj, bytes):
            # Does it encode to utf8?
            try:
                return obj.decode("utf8")
            except UnicodeDecodeError:
                return {
                    "$base64": True,
                    "encoded": base64.b64encode(obj).decode("latin1"),
                }
        return json.JSONEncoder.default(self, obj)