【问题标题】:JSON multiple queries at onceJSON一次多个查询
【发布时间】:2019-04-08 11:33:26
【问题描述】:

我有一个捕获以下 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

那么我怎样才能在同一行代码中捕获值?

【问题讨论】:

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


    【解决方案1】:

    首先,您需要将 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'
    

    【讨论】:

    • @Esteban G. Gutierrez 如果它帮助您将其标记为已解决,请接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2020-07-17
    • 2013-03-16
    • 1970-01-01
    相关资源
    最近更新 更多