當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。