簡體   English   中英

Python 遍歷 json object 內部的數組

[英]Python iterate through an array inside json object

這里有點丟失......試圖在 json object 中迭代這個數組:

{
"NULSBUSD": {
    "symbol": "NULSBUSD",
    "orderId": 33523092,
    "orderListId": -1,
    "clientOrderId": "54Re4e4iV0bCkIXKyth4Sc",
    "transactTime": 1659875121897,
    "price": "0.00000000",
    "origQty": "187.00000000",
    "executedQty": "187.00000000",
    "cummulativeQuoteQty": "50.10100000",
    "status": "FILLED",
    "timeInForce": "GTC",
    "type": "MARKET",
    "side": "BUY",
    "fills": [
        {
            "price": "0.26790000",
            "qty": "150.00000000",
            "commission": "0.00009529",
            "commissionAsset": "BNB",
            "tradeId": 669893
        },
        {
            "price": "0.26800000",
            "qty": "37.00000000",
            "commission": "0.00002350",
            "commissionAsset": "BNB",
            "tradeId": 669894
        }
    ],
    "delta": 0,
    "tsp": 0.264528
}

}

這段代碼拋出

字符串索引必須是整數

qty = 0.0
for coin in order:
for fill in coin['fills']:
qty += float(fill['qty'])

任何想法我如何 go 關於它? 謝謝!

這就是你需要的:

qty = 0.0
for coin in order:
    obj = order[coin]
    for fill in obj['fills']:
        qty += float(fill['qty'])
print(qty)

您可以在一行中執行此操作:

print(sum(float(fill['qty']) for coin in order for fill in order[coin]['fills']))

Output:

187.0

如果你這樣做:對於 key in order,這里的 key 是一個字符串:)

這里使用 dataframe 來避免循環 -

import pandas as pd
import json

with open("data.json") as f:
    json_data = json.load(f)
 
for coin in json_data:
    df = pd.DataFrame(json_data[coin]["fills"])

df["qty"].astype("float").sum()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM