当前位置: 首页>>代码示例>>Python>>正文


Python json.JSONEncoder方法代码示例

本文整理汇总了Python中json.JSONEncoder方法的典型用法代码示例。如果您正苦于以下问题:Python json.JSONEncoder方法的具体用法?Python json.JSONEncoder怎么用?Python json.JSONEncoder使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在json的用法示例。


在下文中一共展示了json.JSONEncoder方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:MolSSI,项目名称:QCElemental,代码行数:20,代码来源:serialization.py

示例2: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:23,代码来源:__init__.py

示例3: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:taspinar,项目名称:twitterscraper,代码行数:18,代码来源:main.py

示例4: dumps

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:__init__.py

示例5: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:20,代码来源:decorators.py

示例6: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:24,代码来源:plotting.py

示例7: to_json

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:oracc,项目名称:pyoracc,代码行数:27,代码来源:atffile.py

示例8: __init__

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:zarr-developers,项目名称:numcodecs,代码行数:21,代码来源:json.py

示例9: __export_to_json

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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!") 
开发者ID:NiaOrg,项目名称:NiaPy,代码行数:23,代码来源:runner.py

示例10: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:google,项目名称:clusterfuzz,代码行数:23,代码来源:json_utils.py

示例11: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:gcallah,项目名称:indras_net,代码行数:11,代码来源:agent.py

示例12: save_result

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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) 
开发者ID:gcallah,项目名称:indras_net,代码行数:10,代码来源:json_combiner.py

示例13: print_result

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
def print_result():
    """
        Handy function to print result_json
    """
    print(json.JSONEncoder(sort_keys=True, indent=4).encode(result_json)) 
开发者ID:gcallah,项目名称:indras_net,代码行数:7,代码来源:json_combiner.py

示例14: generate_json

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
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)) 
开发者ID:gcallah,项目名称:indras_net,代码行数:14,代码来源:json_generator.py

示例15: default

# 需要导入模块: import json [as 别名]
# 或者: from json import JSONEncoder [as 别名]
def default(self, obj):
        """default."""
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj) 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:7,代码来源:__init__.py


注:本文中的json.JSONEncoder方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。