首页 > 编程语言 > 详细

python 序列化 json, pickle

时间:2017-08-23 00:07:28      阅读:293      评论:0      收藏:0      [点我收藏+]

什么是Json:

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成。Json采用完全独立于语言的文本格式,但是也使用了类似C语言的家族习惯(例如C,C++,C#,Java,JavaScript,Perl,Python等),这些特性,使Json成为理想的交换语言。

对于简单数据类型的encoding 和 decoding:

###encoding

>>> import json
>>> obj=[[1,2,3],(a,b,c),{4:5,6:7},def]
>>> encoding_json=json.dumps(obj)
>>> print(encoding_json)
[[1, 2, 3], ["a", "b", "c"], {"4": 5, "6": 7}, "def"] #注意这里元组转化为列表
>>> print(repr(obj))
[[1, 2, 3], (a, b, c), {4: 5, 6: 7}, def]  #这里只是转化为字符串

>>> json.dumps({‘b‘:4,‘a‘:5,‘e‘:6})
‘{"a": 5, "b": 4, "e": 6}‘
>>> json.dumps({‘b‘:4,‘a‘:5,‘e‘:6},sort_keys=True)
‘{"a": 5, "b": 4, "e": 6}‘
>>> a = json.dumps({‘b‘:4,‘a‘:5,‘e‘:6},sort_keys=True,indent=5)#indent指明缩进为5
>>> print(a)
{
     "a": 5,
     "b": 4,
     "e": 6
}

在Json的编码过程中,会存在从Python数据类型向Json类型的转化。

Python Json
dict object
list,tuple array
str string
int,float number
True true
False false
None null
## decode
>>> encoding_json
[[1, 2, 3], ["a", "b", "c"], {"4": 5, "6": 7}, "def"]
>>> decoding_json=json.loads(encoding_json)
>>> print(decoding_json)
[[1, 2, 3], [a, b, c], {4: 5, 6: 7}, def]
>>> type(decoding_json)
<class list>
>>> print(decoding_json[2][4])
5

从Json到Python的数据类型转化对照如下:

JSON Python
object dict
array list
string unicode
number int,long
ture True
false False
null None

python 序列化 json, pickle

原文:http://www.cnblogs.com/frankb/p/7414253.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!