【发布时间】:2020-04-29 06:39:01
【问题描述】:
我从 Python API 调用证券交易所获得以下响应以获取最近的交易价格:
{'exchange': 'NSE', 'token': 1594, 'ltp': 660.7, 'ltt': 1588069745, 'ltq': 2, 'volume': 7296594, 'best_bid_price': 660.7, 'best_bid_quantity': 4864, 'best_ask_price': 0.0, 'best_ask_quantity': 0, 'total_buy_quantity': 4864, 'total_sell_quantity': 0, 'atp': 659.87, 'exchange_time_stamp': 1588069757, 'open': 673.0, 'high': 677.0, 'low': 653.05, 'close': 658.0, 'yearly_high': 847.0, 'yearly_low': 509.25, 'instrument': Instrument(exchange='NSE', token=1594, symbol='INFY', name='INFOSYS LIMITED', expiry=None, lot_size=None)}
我想检索每个项目,如 ltp、ltt、volume 等。 在下面尝试:
msg="{'exchange': 'NSE', 'token': 1594, 'ltp': 660.7, 'ltt': 1588069745, 'ltq': 2, 'volume': 7296594, 'best_bid_price': 660.7, 'best_bid_quantity': 4864, 'best_ask_price': 0.0, 'best_ask_quantity': 0, 'total_buy_quantity': 4864, 'total_sell_quantity': 0, 'atp': 659.87, 'exchange_time_stamp': 1588069757, 'open': 673.0, 'high': 677.0, 'low': 653.05, 'close': 658.0, 'yearly_high': 847.0, 'yearly_low': 509.25, 'instrument': Instrument(exchange='NSE', token=1594, symbol='INFY', name='INFOSYS LIMITED', expiry=None, lot_size=None)}"
res=json.dumps(msg)
res2=json.loads(res)
print(type(res))
print(type(res2))
print(res2['ltp'])
Output :
<class 'str'>
<class 'str'>
Traceback (most recent call last):
File "temp.py", line 11, in <module>
print(res2['ltp'])
TypeError: string indices must be integers
这不是将上述 json 数据转换为 Python 列表。
如何解析这些数据?
【问题讨论】:
-
你为什么使用
json.dumps? -
您的意思是:res=json.loads(msg) 吗?