tonglin0325的个人主页

使用Python解析JSON数据

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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")





 

json.dumps : dict转成str,将字典转换为字符串

json.loads:str转成dict,将字符串转换为字典

参考:json.dumps和 json.loads 区别,如此简单