关闭

Python中的JSON

197人阅读 评论(0) 收藏 举报
分类:
读入json数据,返回Python对象
json.load(open('1.json','wb',ensure_ascii=False))#从数据流
json.loads(json_str)#从字符串
导出json数据,到文件,到字符串(返回值)
json.dump(dic,open('1.json','wb',ensure_ascii=False))

json.dumps(dic)#格式参数ensure_ascii=False, indent=4, separators=(',', ': ')


dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, 
allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
# 序列化 obj 为 JSON 格式的流写入 fp(file-like object)。

If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
#skipkeys 为真时,dict 的 keys 不是基础类型(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)的一种则不会抛出 TypeError` 异常,而是被忽略!

If ``ensure_ascii`` is true (the default), all non-ASCII characters in the
output are escaped with ``\uXXXX`` sequences, and the result is a ``str``
instance consisting of ASCII characters only.  If ``ensure_ascii`` is
``False``, some chunks written to ``fp`` may be ``unicode`` instances.
This usually happens because the input contains unicode strings or the
``encoding`` parameter is used. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter``) this is likely to
cause an error.
 #ensure_ascii 为真(默认)时:所有在输出中的非 ASCII 字符都将转为 ascii 字符(也就是说结果是 1 个只包含 ASCII 字符的 str 实例),如果不能正确转码(中文之类的)则抛出异常!
 #ensure_ascii 为假时:一些写入 fp 的块可能为 Unicode 实例。这通常是因为输入包含 Unicode 字符串或编码参数设置所致。除非 “fp.write() 清楚地知道这是 Unicode 字符串(如同 codecs.getwriter),否则可能会导致错误。

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).
 #check_circular 为 false 时:循环引用检查容器类型将被跳过,循环引用将导致一个 overflowerror 异常(或更糟)。

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.  Since the default item separator is ``','``,  the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ':')`` to avoid this.
#indent:格式化输出!默认 None 为最紧凑的格式。只能为非负整数,设置为 0 的时候为换行!和 separators 结合起来使用!

If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(',', ':')`` separators.
``(',', ':')`` is the most compact JSON representation.
#separators 压缩数据

``encoding`` is the character encoding for str instances, default is UTF-8.
#设置编码

``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.


dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, 
cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
Serialize ``obj`` to a JSON formatted ``str``.
#序列化 obj 为一个 json 字符串!

If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
 
 
If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and
the return value may be a ``unicode`` instance. See ``dump`` for details.
 
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.  Since the default item separator is ``','``,  the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ':')`` to avoid this.
 
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(',', ':')`` separators.
``(',', ':')`` is the most compact JSON representation.
 
``encoding`` is the character encoding for str instances, default is UTF-8.
 
``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.

load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, 
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
# 反序列化 fp(包含 JSON 结构的 file-like object) 为 Python 对象

If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
#如果 fp 的内容是基于 ASCII 编码而不是 UTF-8(如 latin-1)则必须指定 encoding 的名字,。编码是不允许不是基于 ASCII 编码的(如 UCS-2),而应该用 `codecs.getreader(fp)(encoding),或简单地解码为 Unicode 对象传递给 loads()。 

``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
#object_hook 是将要被一些对象逐字解码(一个 dict)的结果调用的一个可选的函数。object_hook 的返回值将用来代替 dict。将来可以使用此功能来实现自定义解码器。

``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs.  The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
 
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.

loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, 
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
 #反序列化 s(一个 JSON 标准的 str 或者 unicode 实例)为 Python 对象。

If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
#如果 s 是一个 str 实例并且是基于 ASCII 编码而不是 utf-8 编码,则必须指定 encoding 的名字。 编码是不允许不是基于 ASCII 编码的(如 UCS-2),并且首先解码为 unicode   

``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
 
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs.  The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
 
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
 
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
 
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
 
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    文章分类