Python处理JSON

来源:互联网 发布:暴走大事件淘宝 编辑:程序博客网 时间:2024/06/11 17:54

转载一:http://blog.csdn.net/woshicsdn7547/article/details/36901291
转载二:http://blog.csdn.net/hellovictoria/article/details/42236753
jso官方说明参见:http://json.org/
Python操作json的标准api库参考:http://docs.python.org/library/json.html

基本概念

  • 序列化(Serialization):将对象的状态信息转换为可以存储或可以通过网络传输的过程,传输的格式可以是JSON、XML等。反序列化就是从存储区域(JSON,XML)读取反序列化对象的状态,重新创建该对象。
  • JSON(JavaScript Object Notation):一种轻量级数据交换格式,相对于XML而言更简单,也易于阅读和编写,机器也方便解析和生成,Json是JavaScript中的一个子集。Python2.6开始加入了JSON模块,无需另外下载,Python的Json模块序列化与反序列化的过程分别是 encoding和 decoding
  • encoding:把一个Python对象编码转换成Json字符串
  • decoding:把Json格式字符串解码转换成Python对象
  • 对于简单数据类型(string、unicode、int、float、list、tuple、dict),可以直接处理。

python解析json的简单例子:

#-*- coding: UTF-8 -*-import json#Function:Analyze json script#Json is a script can descript data structure as xml,#for detail, please refer to "http://json.org/json-zh.html".#Note:#Also, if you write json script from python,#you should use dump instead of load. please refer to "help(json)".#json file:#The file content of temp.json is:#{# "name":"00_sample_case1",# "description":"an example."#}f = file("jsonExample.json")jstr = json.load(f)f.close()print jstr   ##output: {u'name': u'00_sample_case1', u'description': u'an example.'}print type(jstr)   ##output: <type 'dict'>#json string:s = json.loads('{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}')print type(s)   ##output: <type 'dict'>print type(s.keys())    ##output: <type 'list'>print s.keys()   ##output: [u'type', u'name']print s["name"]     ##output: testprint s["type"]["parameter"][1]     ##output: 2

json.dumps方法对简单数据类型encoding:

#-*- coding: UTF-8 -*-import json##对简单数据类型进行encoding,即把一个python对象编码转换成Json字符串data = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象print "DATA:",repr(data)    ###output: DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}]encodedjson= json.dumps(data)print type(encodedjson)    ###output: <type 'str'>print "JSON:", encodedjson   ###output: JSON: [{"a": "A", "c": 3.0, "b": [2, 4]}]data2 = {'a': None, 'b': False, 'c': True}dStr2 = json.dumps(data2)print dStr2     ###output,python对象到Json,一些类型会进行变换: {"a": null, "c": true, "b": false}

JSON的输出结果与DATA很相似,除了一些微妙的变化,如python的元组类型变成了Json的数组,Python到Json的编码转换规则是:
这里写图片描述

json.dumps()方法返回了一个str对象encodedjson,我们接下来在对encodedjson进行decode,即将JSON格式字符串转换成Python对象,得到原始数据,需要使用的json.loads()函数:

decodejson = json.loads(dStr)print type(decodejson)       ###output: <type 'list'>print decodejson         ###output: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]print decodejson[0]['a']        ###output: A

通过输出的结果可以看出,简单类型通过encode之后跟其原始的repr()输出结果非常相似,但是有些数据类型进行了改变,例如上例中的元组则转换为了列表。在json的编码过程中,会存在从python原始类型向json类型的转化过程,具体的转化对照如下:
这里写图片描述

json.dumps方法提供了很多好用的参数可供选择,比较常用的有sort_keys(对dict对象进行排序,我们知道默认dict是无序存放的),separators,indent等参数。

sort_keys, 对dict对象根据key进行排序:

#-*- coding: UTF-8 -*-import jsondata = {'b':789,'c':456,'a':123}d1 = json.dumps(data)d2 = json.dumps(data, sort_keys=True)print d1print d2

输出:
{“a”: 123, “c”: 456, “b”: 789}
{“a”: 123, “b”: 789, “c”: 456}
但是由于dict存储的无序特性,造成两者无法比较。因此两者可以通过排序后的结果进行存储 就避免了数据比较不一致的情况发生,但是排序后再进行存储,系统必定要多做一些事情,也一定会因此造成一定的性能消耗,所以适当排序是很重要的。

indent参数是缩进的意思,它可以使得数据存储的格式变得更加优雅:

d3 = json.dumps(data, sort_keys=True, indent=4)print d3

输出:
{
“a”: 123,
“b”: 789,
“c”: 456
}
输出的数据被格式化之后,变得可读性更强,但是却是通过增加一些冗余的空白格来进行填充的。

json主要是作为一种数据通信的格式存在的,而网络通 信是很在乎数据的大小的,无用的空格会占据很多通信带宽,所以适当时候也要对数据进行压缩。separator参数可以起到这样的作用,该参数传递是一个 元组,包含分割对象的字符串。

print json.dumps(data)print 'dumps(data)   :', len(json.dumps(data))print json.dumps(data, indent=4)print 'dumps(data, indent=4)   :', len(json.dumps(data, indent=4))print json.dumps(data, separators=(',',':'))print 'dumps(data, separators)   :', len(json.dumps(data, separators=(',',':')))

输出:
{“a”: 123, “c”: 456, “b”: 789}
dumps(data) : 30
{
“a”: 123,
“c”: 456,
“b”: 789
}
dumps(data, indent=4) : 46
{“a”:123,”c”:456,”b”:789}
dumps(data, separators) : 25
通过移除多余的空白符,达到了压缩数据的目的,而且效果还是比较明显的。

dumps的另一参数skipkeys,默认为False。 dumps方法存储dict对象时,key必须是str类型,如果出现了其他类型的话,那么会产生TypeError异常,如果开启该参数,设为True的话,则会比较优雅的过度。

data = {'b':789,'c':456,(1,2):123}print json.dumps(data,skipkeys=True)

输出:
{“c”: 456, “b”: 789}

0 0
原创粉丝点击