了解json的人都知道,它是作为传递数据来使用的。其实dump()和dumps()两者区别不大,功能差不多。dumps()是将字典类型数据(dict)转换为字符串类型数据(str),与之对应的loads()则是将字符串类型数据(str)转换成字典类型(dict),仅仅涉及到数据类型的转化,没有涉及文件操作。现在来说一下dump()和load(),dump()也有转换数据类型的功能,与dumps()一样,但是添加了文件操作,调用格式如dump(data, fp),data为字典类型数据,fp为文件操作(一般为写入操作“w”),对应的load()使用方法即为load(fp),fp一般为只读操作“r”。区别介绍完了,下面看看代码实例,可以帮助更加直观地理解其用法。
代码示例:
1、dumps()和loads()
import json dic = {'name': 'wang', 'age': 29} Str = json.dumps(dic) print(Str, type(Str)) data = json.loads(Str) print(data, type(data))
输出结果:
{"name": "wang", "age": 29} <class 'str'>
{'name': 'wang', 'age': 29} <class 'dict'>
2、dump()和load()
import json dic = {'name': 'wang', 'age': 29} fp = open('test.txt', 'w') json.dump(dic, fp) fp.close() fp = open('test.txt','r') print(json.load(fp))
输出结果:
{'name': 'wang', 'age': 29}
打开test.txt文件,即可见如图所示结果,数据已经成功写入test.txt文件中。
总结
通过以上两个简单的例子,应该就能区分出dumps()和dump()的不同用法。如果还想更加详细的了解两者的具体参数及其用法,例如可以使用help(json.dump)命令查看dump()详细的官方使用说明文档,其余的可以自行查询,此处仅以dump()为例子。
import json help(json.dump)Help on function dump in module json:
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).
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.