关于json中的dump()和dumps()及对应的load()和loads()用法上的区别

      了解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.


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值