0
所以我試圖解析來自Google Financial API的數據。我已經爲單股報價工作,但多個股票報價不起作用。 json loads
不適用於多個字典。Python拆分字符串與多個字典
import urllib.request
import json
import time
def get_stock(url, y):
data = urllib.request.urlopen(url)
read = data.read().decode('UTF-8')
json_data = json.loads(read[5:-2])
for n in range(int(len(y.replace(",", ""))/4)):
print(y[4*n:4*n+4].upper(), json_data['l'])
x = ''
while x != 'exit':
x = input("Enter how often, in minutes (minimum one minute), you want the stock price to be updated; or type 'exit': ")
z = input("Enter the market that your stock(s) are in: ")
y = input("Enter the stock(s) that you want to retrieve information for (use commas if neccesary); or type 'exit': ")
y = y.replace(" ", "")
url = 'http://finance.google.com/finance/info?client=ig&q=%s:%s' % (z, y)
while True:
get_stock(url, y)
leave = input("Type 'exit' to leave, or wait until the next quote: ")
if leave == 'exit':
break
time.sleep(int(x))
下面是從谷歌API輸出的JSON的一個例子:
{
"id": "304466804484872"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "496.18"
,"l_fix" : "496.18"
,"l_cur" : "496.18"
,"s": "2"
,"ltt":"4:14PM EST"
,"lt" : "Jan 13, 4:14PM EST"
,"lt_dts" : "2015-01-13T16:14:24Z"
,"c" : "+3.63"
,"c_fix" : "3.63"
,"cp" : "0.74"
,"cp_fix" : "0.74"
,"ccol" : "chg"
,"pcls_fix" : "492.55"
,"el": "497.00"
,"el_fix": "497.00"
,"el_cur": "497.00"
,"elt" : "Jan 13, 7:59PM EST"
,"ec" : "+0.82"
,"ec_fix" : "0.82"
,"ecp" : "0.17"
,"ecp_fix" : "0.17"
,"eccol" : "chg"
,"div" : ""
,"yld" : ""
}
,{
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "110.22"
,"l_fix" : "110.22"
,"l_cur" : "110.22"
,"s": "2"
,"ltt":"4:14PM EST"
,"lt" : "Jan 13, 4:14PM EST"
,"lt_dts" : "2015-01-13T16:14:23Z"
,"c" : "+0.97"
,"c_fix" : "0.97"
,"cp" : "0.89"
,"cp_fix" : "0.89"
,"ccol" : "chg"
,"pcls_fix" : "109.25"
,"el": "110.30"
,"el_fix": "110.30"
,"el_cur": "110.30"
,"elt" : "Jan 13, 7:59PM EST"
,"ec" : "+0.08"
,"ec_fix" : "0.08"
,"ecp" : "0.07"
,"ecp_fix" : "0.07"
,"eccol" : "chg"
,"div" : "0.47"
,"yld" : "1.71"
}
我似乎無法找到一個有效的解決方案。 split
方法不會工作,因爲字符串中無處不在的逗號。 linesplit
將無法工作,因爲衆多的\n
換行符。
我只是需要得到字符串拆分,所以我可以使用json dumps
,然後對每個使用json loads
運行迭代來解析數據以進行訪問。
完美,感謝布魯諾。這是我最初的想法,但不幸的是,我試圖通過混合類型來添加括號,並以實際列表對象而不是str添加結束。 – roflmyeggo