解析json.dumps - Python

时间:2016-06-22 15:46:18

标签: python json python-2.7 parsing

我调用了一个返回以下JSON的API:

{
"trades": [
    {
        "stopLoss": 154.79, 
        "takeProfit": 151.79, 
        "price": 153.784, 
        "side": "sell", 
        "trailingStop": 0, 
        "instrument": "GBP_JPY", 
        "time": "2016-06-21T18:20:24.000000Z", 
        "units": 25, 
        "id": 10297636517, 
        "trailingAmount": 0
    }
]
}

我在解析时遇到问题,所以我只返回" id"和#34;价格"。由于我还不了解的原因,我可以在['trades']之后添加tradeId=response,它会按预期深入到此处。但我不能把它简化为只是" id"和"价格"。我怎样才能解析数据,json.dumps是最佳方法?在此先感谢您的帮助!

{
        "stopLoss": 154.79, 
        "takeProfit": 151.79, 
        "price": 153.784, 
        "side": "sell", 
        "trailingStop": 0, 
        "instrument": "GBP_JPY", 
        "time": "2016-06-21T18:20:24.000000Z", 
        "units": 25, 
        "id": 10297636517, 
        "trailingAmount": 0
    }

代码:

response = oanda.get_trades(account_id)

def transactions():
    while response:
        tradeId = response
        ids = tradeId
        line = json.dumps(ids, indent=4)
        print line
        return
print transactions()

2 个答案:

答案 0 :(得分:1)

您可以使用 json.loads()来解析json。

import json
response = '{"trades": [{"stopLoss": 154.79, "takeProfit": 151.79, "price": 153.784, "side": "sell", "trailingStop": 0, "instrument": "GBP_JPY", "time": "2016-06-21T18:20:24.000000Z", "units": 25, "id": 10297636517, "trailingAmount": 0}]}'

def transactions():
    json_tree = json.loads(response)
    trade_list = json_tree['trades']
    trade = trade_list[0]
    return (trade['id'], trade['price'])

print transactions()

答案 1 :(得分:0)

找出答案。我只是尝试['trades']['id']而不是 ['trades'][0]['id'] ..谢谢