20180212第一发:Python与Json编码解码举例

dumps是将dict转化成str格式,loads是将str转化成dict格式。

dump和load也是类似的功能,只是与文件操作结合起来了

>>> import json

>>> c = {"name": "wang", "age": 30}

>>> print(type(c))

<class 'dict'>

>>> c1 = json.dumps(c)               #pyhon对象encode为json字符串

>>> print(c1)

{"name": "wang", "age": 30}

>>> print(type(c1))

<class 'str'>

>>> c2 = json.loads(c1)               #json字符串decode为python对象

>>> print(c2)

{'name': 'wang', 'age': 30}

>>> print(type(c2))

<class 'dict'>

字符串例子:

>>> c = ["avf",432,'ddd',{'f':123,'g':'ggg'}]

>>> print(c,type(c))

['avf', 432, 'ddd', {'f': 123, 'g': 'ggg'}] <class 'list'>           #list,dict都是单引号

>>> c1 = json.dumps(c)

>>> print(c1,type(c1))

["avf", 432, "ddd", {"f": 123, "g": "ggg"}] <class 'str'>          #str 都是双引号

>>> c1 = json.loads(c1)

>>> print(c1,type(c1))

['avf', 432, 'ddd', {'f': 123, 'g': 'ggg'}] <class 'list'>

原文地址:https://www.cnblogs.com/hazelrunner/p/8444744.html