json格式数据默认为string,可以使用eval()函数或者json模块将其转换为dict.标准Json字符串必须使用双引号(")而不能使用单引号(‘),否则从字符串转换成dict类型会提示出错。
方法一(使用eval函数):
# -*- coding: UTF-8 -*- import urllib2 url=‘http://www.weather.com.cn/data/cityinfo/101010100.html‘ req = urllib2.Request(url) res = urllib2.urlopen(req).read() res_d = eval(res) # use eval() to convert json string to dict. eval():将字符串str当成有效的表达式来求值并返回计算结果 print type(res_d) print res_d[‘weatherinfo‘][‘city‘] print res_d[‘weatherinfo‘][‘temp1‘] print res_d[‘weatherinfo‘][‘temp2‘]
返回结果:
<type ‘dict‘>
北京
-2℃
16℃
方法二(使用JSONDecoder):
# -*- coding: UTF-8 -*- import urllib2,sys from json import * reload(sys) sys.setdefaultencoding(‘utf-8‘) url=‘http://www.weather.com.cn/data/cityinfo/101010100.html‘ req = urllib2.Request(url) res = urllib2.urlopen(req).read() res_d = JSONDecoder().decode(res) print type(res_d) print res_d[‘weatherinfo‘][‘city‘] print res_d[‘weatherinfo‘][‘temp1‘] print res_d[‘weatherinfo‘][‘temp2‘]
将dict转换为json:
JSONEncoder().encode(res_d)
方法三(使用json):
#dict convert to json string. res = json.dumps(res_d) print type(res) #json string convert to dict. res_d = json.loads(res) print type(res_d)
附:
res返回值(json):
{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"-2℃","temp2":"16℃","weather":"晴","img1":"n0.gif","img2":"d0.gif","ptime":"18:00"}}
res_d返回值(dict):
{u‘weatherinfo‘: {u‘city‘: u‘\u5317\u4eac‘, u‘ptime‘: u‘18:00‘, u‘cityid‘: u‘101010100‘, u‘temp2‘: u‘16\u2103‘, u‘temp1‘: u‘-2\u2103‘, u‘weather‘: u‘\u6674‘, u‘img2‘: u‘d0.gif‘, u‘img1‘: u‘n0.gif‘}}
eval()函数用法:http://www.tuicool.com/articles/BBVnQbq
原文:http://www.cnblogs.com/dreamer-fish/p/5377603.html