Parsing json.dumps - Python

advertisements

I have a call to an API that returns the following JSON:

{
"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
    }
]
}

I'm having trouble parsing so that I only return the "id" and the "price". For reasons I don't understand yet, i can add ['trades'] after tradeId=response and it will drill down to just this, as expected. But i cannot get it whittled down to just "id" and "price". How could I go about parsing the data, and is json.dumps the optimal method? Thanks in advance for the help!

{
        "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
    }

code:

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()


You can use json.loads() to parse the 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()