解析json.dumps-Python [英] Parsing json.dumps - Python

查看:168
本文介绍了解析json.dumps-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对返回以下JSON的API进行了调用:

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

我在解析时遇到了麻烦,因此我只能返回"id"和"price".由于我尚不了解的原因,我可以在tradeId=response之后添加['trades'],它将按预期深入到此.但是我无法将其缩减为"id"和"price".我该如何解析数据,并且json.dumps是最佳方法?预先感谢您的帮助!

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
    }

代码:

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

推荐答案

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

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

这篇关于解析json.dumps-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆