2016-03-03 43 views
-1

我能够使用谷歌的API金融,但它今天停止工作,所以我一直在寻找替代品。将字符串转换为给定python输出格式的字典

我试着去实现谷歌财务模块和下面是我尝试它

from googlefinance import getQuotes 
import json 
import time 
import ast 

y = json.dumps(getQuotes('YHOO'), indent=2) 

print y 
print type(y) 
print len(y) 
price = y[275] 
print price 



##where i wanna be able to update the stock price 
#while True: 

    #time.sleep(3) 

然后我得到下面的输出,

[ 
    { 
    "Index": "NASDAQ", 
    "LastTradeWithCurrency": "32.58", 
    "LastTradeDateTime": "2016-03-03T11:54:19Z", 
    "LastTradePrice": "32.58", 
    "LastTradeTime": "11:54AM EST", 
    "LastTradeDateTimeLong": "Mar 3, 11:54AM EST", 
    "StockSymbol": "YHOO", 
    "ID": "658890" 
    } 
] 
<type 'str'> 
292 
[ 

我知道,如果我切它为y= y[1:len(y)-1]和摆脱[]的原始输出,它的格式为dict
不知道该从哪里出发。 (我知道,如果我只是复制切片后的输出,并将其分配给一个新的变量,它存储为一个字典)

+1

'getQuotes()'将数据作为python对象返回。为什么要将它转储到json字符串中,只是试图将该字符串转换回python对象? –

+0

我希望输出是一个字典,所以我可以通过参考键来挑选我想要的东西 – stratofortress

+0

'getQuotes'返回一个字典列表。只要做'getQuotes('YHOO')[0] ['StockSymbol']' –

回答

0

我假设getQuotes返回一个列表包含一个项目是一个字典。如果你想获得只是字典没有列表,然后使用索引提取它:

my_dict = getQuotes('YHOO')[0] 
0

因为getQotes()回报与dictlist,没有理由先jsonify它。

from googlefinance import getQuotes 
import json 

yhoo = getQuotes('YHOO')[0] 
jsonyhoo = json.dumps(yhoo, indent=2) 
assert type(yhoo) is dict 
assert type(jsonyhoo) is str 

顺便说一句,你不需要运行:

someString[1:len(someString)-1] 

你可以简单地做:

someString[1:-1] 

达到相同的效果。