先解释一些
概念
序列化(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),可以直接处理。
我是想从网页的URL获得的json数据里面提取价格信息,代码如下:
# -*- coding: utf-8 -*-
import sys
import urllib2
import json
reload(sys)
sys.setdefaultencoding('utf8')
html=urllib2.urlopen(r'http://flights.ctrip.com/domesticsearch/search/SearchFirstRouteFlights?DCity1=SHA&ACity1=BJS&SearchType=S&DDate1=2016-09-25')
#json.dumps(html, ensure_ascii=False)
hjson = json.loads(html.read())
print hjson['lps']['2016-09-25']
然后运行之后报错:
(unicode error) 'utf-8' codec can't decode byte 0xbb in position 0
这个的意思就是说decode的时候utf-8这种编码模式不能解决我的json数据格式。经过请教师兄得知,一般json的编码方式有两种:utf-8和GBK,所以一种不行就试试另外一种,也就是该成以下形式:
# -*- coding: utf-8 -*-
import sys
import urllib2
import json
reload(sys)
sys.setdefaultencoding('utf8')
html=urllib2.urlopen(r'http://flights.ctrip.com/domesticsearch/search/SearchFirstRouteFlights?DCity1=SHA&ACity1=BJS&SearchType=S&DDate1=2016-09-25')
#json.dumps(html, ensure_ascii=False)
hjson = json.loads(html.read().decode('GBK'))#改动在这里
print hjson['lps']['2016-09-25']
这时候运行就成功了。
关于编码的其他形式http://blog.youkuaiyun.com/u011350122/article/details/51192826?locationNum=12