Home  >  Article  >  Backend Development  >  python解析json实例方法

python解析json实例方法

WBOY
WBOYOriginal
2016-06-16 08:46:151184browse

最近在做天气业务的延时监控,就是每隔一个小时检查一次天气数据是否变化,三次不变化就报警。由于页面给的数据的以json格式的,所以如何解析页面上的数据,从而获得我们想要的字段是我们首先考虑的问题。
一般来说,当我们从一个网页上拿下来数据,就是一个字符串,比如:

复制代码 代码如下:

url_data = urllib2.urlopen(url).readline()


当我们这样得到页面数据,url_data是全部页面显示一个json字符串,那么我们如何将这个字符串转变为字典格式:time = json.loads(url_data)["weatherinfo"]["time"]

通过json模块的函数loads()可以将原来的字符串编码为字典,这样我们想去查找一个字段的key值就方便多了。
部分代码如下:

复制代码 代码如下:

def getTime(url):
        url_data = urllib2.urlopen(url).readline()
        print url_data
        time = json.loads(url_data)["weatherinfo"]["time"]
        return time
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn