json,json扩展

Posted 986428528

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json,json扩展相关的知识,希望对你有一定的参考价值。

#参数1:obj(基本数据类型) 参数2:fp=open(file)
def
dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). #具备f.write()的功能 If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the strings written to ``fp`` can contain non-ASCII characters if they appear in strings contained in ``obj``. Otherwise, all such characters are escaped in JSON strings. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the javascript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If specified, ``separators`` should be an ``(item_separator, key_separator)`` tuple. The default is ``(‘, ‘, ‘: ‘)`` if *indent* is ``None`` and ``(‘,‘, ‘: ‘)`` otherwise. To get the most compact JSON representation, you should specify ``(‘,‘, ‘:‘)`` to eliminate whitespace. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *sort_keys* is true (default: ``False``), then the output of dictionaries will be sorted by key. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and default is None and not sort_keys and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk)
class JSONEncoder(object):
#默认json只能序列化基本数据类型
"""Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """

def default(self, o):                   #默认会报错
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).

For example, to support arbitrary iterators, you could
implement default like this::

def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return JSONEncoder.default(self, o)

"""
raise TypeError("Object of type ‘%s‘ is not JSON serializable" %
o.__class__.__name__)
 

扩展json可以序列化的类型:

扩展的实质就是扩展JSONEncoder 的 default 方法

import json as default_json             
from json.encoder import JSONEncoder
from .response import BaseResponse

class JsonEncoder(JSONEncoder):   #继承JSONEncoder
    def default(self, o):                  #写default 方法
        if isinstance(o,BaseResponse):
            return o.__dict__
        return JSONEncoder.default(self,o)
class Json(object):             #自定义的Json
    @staticmethod
    def dumps(response,ensure_ascii=True):       #自定义的dumps
        return default_json.dumps(response,ensure_ascii=ensure_ascii,cls=JsonEncoder)    
#自定义的dumps返回系统(json)的dumps方法,但是cls是扩展的JsonEncoder

To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

"""

 















以上是关于json,json扩展的主要内容,如果未能解决你的问题,请参考以下文章

json 可视代码工作室Angular with Firebase片段

vs code 用户代码片段 html.json

错误代码:错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象和允许未设置片段的选项开头。”

VS Code配置snippets代码片段快速生成html模板,提高前端编写效率

如何在android中将json数据加载到片段中

使用 json rereiver php mysql 在片段中填充列表视图