一次JSON多个查询

时间:2018-11-05 05:25:38

标签: json python-3.x error-handling

我有一个捕获以下JSON信息的python方法:

{'info': {'orderId': 5913316, 'clientOrderId': 'ME_dot', 'origQty': '0.02000000', 'trade': 'xxx', 'updateTime': xxx, 'side': 'BUY', 'timeInForce': 'GTC', 'status': 'FILLED', 'stopPrice': '0.0', 'time': xxx, 'isWorking': True, 'type': 'LIMIT', 'price': '506.10887700', 'executedQty': '0.02000000'}, 'lastTradeTimestamp': None, 'remaining': 0.0, 'fee': None, 'timestamp': x, 'symbol': 'xxx', 'trades': None, 'datetime': 'xxx, 'price': 0.108877, 'amount': 0.02, 'cost': 0.00217754, 'status': 'closed', 'type': 'limit', 'id': '59139516', 'filled': 0.02, 'side': 'buy'}

从中,我只需要捕获clientOrderIdexecutedQty,所以我尝试以下操作:

id, q  =  (exchange.order_status(trading )['info']['clientOrderId'], ['info']['executedQty'])
出现此问题的

TypeError: list indices must be integers, not str

那么我该如何捕获同一行代码中的值?

1 个答案:

答案 0 :(得分:2)

首先,您需要将JSON字符串转换为JSON对象。但是问题中的json格式不正确,无法直接进行转换。所以,

正确地将您的JSON封装在""中。这是格式正确的。

order_status = '{"info": {"orderId": 5913316, "clientOrderId": "ME_dot", "origQty": "0.02000000", "trade": "xxx", "updateTime": "xxx", "side": "BUY", "timeInForce": "GTC", "status": "FILLED", "stopPrice": "0.0", "time": "xxx", "isWorking": "True", "type": "LIMIT", "price": "506.10887700", "executedQty": "0.02000000"}, "lastTradeTimestamp": "None", "remaining": 0.0, "fee": "None", "timestamp": "x", "symbol": "xxx", "trades": "None", "datetime": "xxx", "price": 0.108877, "amount": 0.02, "cost": 0.00217754, "status": "closed", "type": "limit", "id": "59139516", "filled": 0.02, "side": "buy"}'

完成后,

import json
order_status_json = json.loads(order_status) 

这会将字符串转换为JSON对象,现在您可以轻松查询值。

喜欢这个

p, q  =  (order_status_json['info']['clientOrderId'],order_status_json['info']['executedQty'])

返回

>>> p

'ME_dot'
>>> q

'0.02000000'