访问json数组对象中的数据

2024-04-25 21:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一个数组结构,我得到的是json。我需要访问这个数组结构中的一些元素

‘资产’:[{‘资产’:‘USDT’

我需要访问其中的walletBalance对象。 我该怎么做

 def account_balance(webhook_data):
     account_data = client.futures_account()
     temp_account_data = json.dumps(account_data)
     test = json.loads(temp_account_data)

     for sym in test:
         print(sym['assets'])
     return account_balance

在上面的代码片段中,对象是json,但我无法访问“资产”内容

{'feeTier': 0, 
'canTrade': True, 
'canDeposit': True, 
'canWithdraw': True, 
'updateTime': 0, 
'totalInitialMargin': '0.00000000', 
'totalMaintMargin': '0.00000000', 
'totalWalletBalance': '32.51609961', 
'totalUnrealizedProfit': '0.00000000', 
'totalMarginBalance': '32.51609961', 
'totalPositionInitialMargin': '0.00000000', 
'totalOpenOrderInitialMargin': '0.00000000', 
'maxWithdrawAmount': '32.51609961', 

'assets': 

[
{'asset': 'USDT', 
'walletBalance': '32.51609961', 
'unrealizedProfit': '0.00000000', 
'marginBalance': '32.51609961', 
'maintMargin': '0.00000000', 
'initialMargin': '0.00000000', 
'positionInitialMargin': '0.00000000', 
'openOrderInitialMargin': '0.00000000', 
'maxWithdrawAmount': '32.51609961'
},

 {'asset': 'BNB', 'walletBalance': '0.00000000', 
'unrealizedProfit': '0.00000000', 'marginBalance': '0.00000000', 
'maintMargin': '0.00000000', 'initialMargin': '0.00000000', 
'positionInitialMargin': '0.00000000', 
'openOrderInitialMargin': '0.00000000',
'maxWithdrawAmount': '0.00000000'}], 



'positions': [
{'symbol': 'EOSUSDT', 'initialMargin': '0', 'maintMargin': '0', 'unrealizedProfit': '0.00000000', 'positionInitialMargin': '0', 'openOrderInitialMargin': '0', 'leverage': '10', 'isolated': False, 'entryPrice': '0.0000', 'maxNotional': '1000000', 'positionSide': 'BOTH'}, 

{'symbol': 'SUSHIUSDT', 'initialMargin': '0', 'maintMargin': '0', 'unrealizedProfit': '0.00000000', 'positionInitialMargin': '0', 'openOrderInitialMargin': '0', 'leverage': '20', 'isolated': False, 'entryPrice': '0.0000', 'maxNotional': '25000', 'positionSide': 'BOTH'}
]}  

3条回答

您可以使用列表理解

res = [x.get('walletBalance') for x in test['assets']]
print(res)

输出:

['32.51609961', '0.00000000']

您似乎正在从呼叫客户端获得一本字典。futures\u account() . 如果是,则不需要转储和加载。 您可以简单地执行以下操作:

 def account_balance(webhook_data):
     account_data = client.futures_account()
     return [x.get('walletBalance') for x in account_data['assets']]

请注意,可能有多个助理,因此在其上循环:

for asset in json_data.get('assets', []):
    print(asset.get('walletBalance'))

相关问题 更多 >