JSON: Python Objects与String之间转换

JSON的dumps()函数可以将python的各种数据类型转换为字符串,loads()函数可以将相应的字符串转换回python变量,例如:
import json
data = [ { ‘a’:’A’, ‘b’:(2, 4), ‘c’:3.0 } ]
data_string = json.dumps(data)
print ‘ENCODED:’, data_string
decoded = json.loads(data_string)
print ‘DECODED:’, decoded
print ‘ORIGINAL:’, type(data[0][‘b’])
print ‘DECODED :’, type(decoded[0][‘b’])

输出为:
ENCODED: [{“a”: “A”, “c”: 3.0, “b”: [2, 4]}]
DECODED: [{u’a’: u’A’, u’c’: 3.0, u’b’: [2, 4]}]
ORIGINAL:
DECODED :

**Note: 字符串被JSON转换为Unicode编码,tuple被JSON转换为list类型。

0
如无特殊说明,文章均为本站原创,转载请注明出处

该文章由 发布

这货来去如风,什么鬼都没留下!!!