Python 获取接口数据,解析JSON,写入文件

Python 获取接口数据,解析JSON,写入文件

用于练手的例子,从国家气象局接口上获取JSON数据,将它写入文件中,并解析JSON;

总的来说,在代码量上,python代码量要比java少很多。而且python看起来更直观一些;

以下是代码:

import types
import urllib2
import json


duan ="--------------------------"	#在控制台断行区别的

#利用urllib2获取网络数据
def registerUrl():
	try:
		url ="http://m.weather.com.cn/data/101010100.html"
		data = urllib2.urlopen(url).read()
		return data
	except Exception,e:
		print e
		
#写入文件
def jsonFile(fileData):
	file = open("d:\json.txt","w")
	file.write(fileData)
	file.close()

#解析从网络上获取的JSON数据	
def praserJsonFile(jsonData):
	value = json.loads(jsonData)
	rootlist = value.keys()
	print rootlist
	print duan
	for rootkey in rootlist:
		print rootkey
	print duan
	subvalue = value[rootkey]
	print subvalue
	print duan
	for subkey in subvalue:
		print subkey,subvalue[subkey]
	
if __name__ == "__main__":
	# xinput = raw_input()
	# x = 130
	# xvalue = cmp(x,xinput)
	# print xvalue
	# print x/100.0
	
	data = registerUrl()
	# jsonFile(data)
	
	praserJsonFile(data)
	
	
posted @ 2017-08-09 23:12  0x03  阅读(14909)  评论(0编辑  收藏  举报