【发布时间】:2020-05-11 07:05:29
【问题描述】:
我正在构建一个股票交易机器人,可以根据我的策略为我交易股票。现在我只是在设置选股功能。
当我尝试 json.loads 或 json.dumps 时,我不断收到 "TypeError: the JSON object must be str, bytes or bytearray, not 'dict'" 或 "TypeError: string indices must be integers"
我想从这个 json 响应中提取“lastPrice”。在这种情况下,lastPrice 将是 135.87
这是我得到的:
data = content.json()
Json 数据(从代理的 api 中提取)
{'WBC': {'assetType': 'EQUITY', 'assetMainType': 'EQUITY', 'cusip': '92927K102', 'symbol': 'WBC', 'description': 'Wabco Holdings Inc. Common Stock', 'bidPrice': 135.76, 'bidSize': 100, 'bidId': 'K', 'askPrice': 136.1, 'askSize': 2000, 'askId': 'P', 'lastPrice': 135.87, 'lastSize': 66100, 'lastId': 'N', 'openPrice': 135.77, 'highPrice': 135.95, 'lowPrice': 135.77, 'bidTick': ' ', 'closePrice': 135.79, 'netChange': 0.08, 'totalVolume': 482625, 'quoteTimeInLong': 1579903320193, 'tradeTimeInLong': 1579908600006, 'mark': 135.87, 'exchange': 'n', 'exchangeName': 'NYSE', 'marginable': True, 'shortable': True, 'volatility': 0.006, 'digits': 2, '52WkHigh': 146.675, '52WkLow': 108.09, 'nAV': 0.0, 'peRatio': 21.29, 'divAmount': 0.0, 'divYield': 0.0, 'divDate': '', 'securityStatus': 'Normal', 'regularMarketLastPrice': 135.87, 'regularMarketLastSize': 661, 'regularMarketNetChange': 0.08, 'regularMarketTradeTimeInLong': 1579908600006, 'netPercentChangeInDouble': 0.0589, 'markChangeInDouble': 0.08, 'markPercentChangeInDouble': 0.0589, 'regularMarketPercentChangeInDouble': 0.0589, 'delayed': True}}
尝试仅打印 135.87
val = json.loads(data)
print(val['lastPrice'])
【问题讨论】:
-
你用的是什么版本的 Python?
-
看来
data已经是dict了。所以试试print( data['WBC']['lastPrice'] )