如何读取嵌套的json转储

时间:2017-10-08 15:16:42

标签: python json

嘿伙计们我正在尝试读取json转储,但不知道如何读取嵌套的json转储,如lastTransactionID或NAV。

我也收到属性错误'AccountDetails'对象没有属性'get。

r = accounts.AccountDetails(accountID)
client.request(r)
print r.response
print r.get('lastTransactionID')
print r.get('NAV')
print r.get('unrealizedPL')

 {
    u'account': 
        {
        u'trades': [], 
        u'marginCloseoutNAV': u'99999.9998',
        u'marginUsed': u'0.0000', 
        u'marginCloseoutPositionValue': u'0.0000', 
        u'currency': u'EUR', 
        u'resettablePL': u'-0.0002', 
        u'NAV': u'99999.9998', 
        u'marginCloseoutMarginUsed': u'0.0000', 
        u'openTradeCount': 0, 
        u'marginCallMarginUsed': u'0.0000', 
        u'orders': [], 
        u'openPositionCount': 0, 
        u'positionValue': u'0.0000', 
        u'pl': u'-0.0002', 
        u'financing': u'0.0000', 
        u'pendingOrderCount': 0, 
        u'positions': 
            [
                    {
                    u'financing': u'0.0000',
                    u'short': 
                        {
                        u'units': u'0', 
                        u'financing': u'0', 
                        u'resettablePL': u'0.0000', 
                        u'unrealizedPL': u'0.0000', 
                        u'pl': u'0.0000'
                        }, 

                    u'commission': u'0.0000', 
                    u'unrealizedPL': u'0.0000', 

                    u'long': 
                        {
                        u'units': u'0', 
                        u'financing': u'0.0000', 
                        u'resettablePL': u'-0.0002', 
                        u'unrealizedPL': u'0.0000', 
                        u'pl': u'-0.0002'
                        }, 

                    u'instrument': u'AUD_USD', 
                    u'resettablePL': u'-0.0002', 
                    u'pl': u'-0.0002'
                    }
            ], 

        u'unrealizedPL': u'0.0000', 
        u'alias': u'Primary', 
        u'createdByUserID': xxx, 
        u'marginCloseoutUnrealizedPL': u'0.0000', 
        u'createdTime': u'2017-05-25T18:26:03.961466233Z', 
        u'balance': u'99999.9998'
        }, 

        u'lastTransactionID': u'255'
    }

有人知道如何从json转储中读取嵌套元素吗? 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以使用json模块:

import json

a = json.load(string_or_file_with_json)
# Now in a you have a dict, that represents json object
# You can write a simple recursive function, that will do something on every entry or smt like that
def do(json_dict):
   for k, v in json_dict.items():
       # !UPDATE, use isinstance(v, dict) instead of v is dict
       # Thx mister in comments
       if isinstance(v, dict): # if v is dict, than it's a nested json object
           do(x)
       else: # else it specific value
           your_action(k, v)