使用Python解析JSON数据

时间:2022-10-03 06:18:09

使用Python解析百度API返回的JSON格式的数据

# coding:utf-8
# !/usr/bin/env python import matplotlib.pyplot as plt
from numpy import *
import sys, urllib, urllib2, json
import fun if __name__ == '__main__':
dataMat,labelMat = fun.loadDataSet("code.txt")
print dataMat[0]
url = 'http://apis.baidu.com/apistore/stockservice/usastock?stockid=CFC-B&list=1'
req = urllib2.Request(url) req.add_header("apikey", "你自己的apikey")
resp = urllib2.urlopen(req)
content = resp.read()
s = json.loads(content) for i in s.keys():
if i == 'errNum':
print '错误码:',s[i]
elif i == 'errMsg':
print '错误信息:',s[i]
else:
for j in s[i].keys():
if j == 'stockinfo':
print "返回数据:",j,":",str(s[i][j]).replace('u\'','\'').decode("unicode-escape")+'\n'
elif j == 'market':
for k in s[i][j].keys():
print k,":",str(s[i][j][k]).replace('u\'','\'').decode("unicode-escape")+'\n'
#print "返回数据:",j,":",str(s[i][j]).replace('u\'','\'').decode("unicode-escape")