python跟json的区别_python的JSON与字典区别

在python中,字典的输出内容跟json格式内容一样,但是字典的格式是字典,json的格式是字符串,所以在传输的时候(特别是网页)要转换使用。

重要函数

编码:把一个Python对象编码转换成Json字符串   json.dumps()

解码:把Json格式字符串解码转换成Python对象   json.loads()

In [1]: import json

In [2]: dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }

In [3]: type(dic)

Out[3]: dict

In [5]: json_obj=json.dump(dic)

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in ()

----> 1 json_obj=json.dump(dic)

TypeError: dump() takes at least 2 arguments (1 given)

In [6]: json_obj=json.dumps(dic)

In [8]: type(json_obj)

Out[8]: str

In [9]: print json_obj

{"sub_dic": {"sub_str": "this is sub str", "sub_list": [1, 2, 3]}, "end": "end", "list": [1, 2, "a", "b"], "str": "this is a string"}

In [10]: dic1=json.loads(json_obj)

In [11]: type(dic1)

Out[11]: dict

In [12]: print dic1

{u'end': u'end', u'list': [1, 2, u'a', u'b'], u'sub_dic': {u'sub_str': u'this is sub str', u'sub_list': [1, 2, 3]}, u'str': u'this is a string'}

In [13]: print dic

{'sub_dic': {'sub_str': 'this is sub str', 'sub_list': [1, 2, 3]}, 'end': 'end', 'list': [1, 2, 'a', 'b'], 'str': 'this is a string'}

参考:https://docs.python.org/dev/library/json.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值