• 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)
    	
    	
  • 相关阅读:
    leetcode 63 简单题
    leetcode 712
    500 问的数学基础
    转载一份kaggle的特征工程:经纬度、特征构造、转化率
    散度
    在线学习在CTR上应用的综述
    广告的计费方式
    矩阵2范数与向量2范数的关系
    text_CNN笔记
    F1
  • 原文地址:https://www.cnblogs.com/0x03/p/7335305.html
Copyright © 2020-2023  润新知