Python中的JSON

原创 2016年06月01日 10:54:37
读入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.



版权声明:本文为博主原创文章,未经博主允许不得转载。

Python解析JSON数据的基本方法

1 JSON数据格式介绍 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 JSON建构于两种结构:简单来说,就是Javascript...
  • ifruoxi
  • ifruoxi
  • 2017年01月03日 15:49
  • 1801

python解析json:json模块

python中解析json字符串非常简单,直接用内置的json模块就可以,不需要安装额外的模块。 一、json字符串转为python值 json字符串: {"userAccount":"54321...
  • yupeigu
  • yupeigu
  • 2016年12月07日 15:18
  • 793

python解析与组装json

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - Decembe...
  • sinat_35059932
  • sinat_35059932
  • 2017年03月08日 18:14
  • 953

python解析json数据

比如json数据为:{"code":0,"desc":"success","content":[{"type":{"id":"2","name":"\u56e2\u8d2d"},"status":{"...
  • xiaodanpeng
  • xiaodanpeng
  • 2016年03月07日 17:28
  • 1901

Python-读入json文件并进行解析及json基本操作

import jsondef resolveJson(path): file = open(path, "rb") fileJson = json.load(file) fie...
  • ko_tin
  • ko_tin
  • 2017年05月18日 16:11
  • 4729

Python接口对json串的处理

最近学习Python接口测试,对于接口测试完全小白。大概一周的学习成果进行总结。 1.接口测试: 目前涉及到的只是对简单单一的接口进行参数传递,得到返回自。 2.关于各种概念: ...
  • dongqiushan
  • dongqiushan
  • 2016年08月26日 16:33
  • 2754

python中的json使用误区

1)  json使用的要点,目前json是网络之间通信的一种数据格式,与xml类似,但它的格式比xml要稍微小一些,由于本项目中数据量会比较大,所以尽量采用较小存储的json格式。 但用json格式...
  • cajeep2001
  • cajeep2001
  • 2013年02月05日 23:18
  • 13199

Python中json格式数据的编码和解码

Python从2.6版本开始内置了json数据格式的处理方法。 1、json格式数据编码 在python中,json数据格式编码使用json.dumps方法。 [pyth...
  • yaya1943
  • yaya1943
  • 2016年11月16日 20:55
  • 461

Python Requests post并将得到结果转换为json

编程小白一个,目前在学习python 爬虫。 之前看到一个博主说些博客对于程序员来说挺重要的,没怎么在意。今天觉得面对一个问题好不容易找到解决方案,是应该记录一下。说不定还有人来讨论讨论,哈哈! 之前...
  • sinat_28680819
  • sinat_28680819
  • 2017年04月28日 20:01
  • 5667

python 读写JSON数据

http://python3-cookbook.readthedocs.org/zh_CN/latest/c06/p02_read-write_json_data.html  问题 ...
  • scdxmoe
  • scdxmoe
  • 2015年11月20日 15:06
  • 1316
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Python中的JSON
举报原因:
原因补充:

(最多只允许输入30个字)