簡體   English   中英

Python json.dumps 格式化

[英]Python json.dumps formatting

我在Parsing json.dumps - Python中嘗試反向操作

我有一個數據框,其中行的格式為:

stopLoss  takeProfit   price    id
154.79     151.79      153.784  0

我想將 output 格式化為 JSON 格式

{
"trades" : [{
         "stopLoss": 154.79, 
        "takeProfit": 151.79, 
        "price": 153.784, 
         "id: :0
        }]

}

在行上使用 json.dumps 會產生 JSON,但“交易”之后的 [ ] 缺失。 如下圖所示:

{
"trades" : {
         "stopLoss": 154.79, 
        "takeProfit": 151.79, 
        "price": 153.784, 
         "id: :0
        }

}

如何確保包含 [ ]?

它會准確轉儲您傳入的結構。如果trades鍵的值是字典列表而不是單個字典,您將獲得所需的 output。 但這與 JSON 無關; 它僅取決於您在json.dumps()的參數中擁有哪些數據。

如果您的代碼看起來像

trades = csvreader.next()
j = {'trades': trades }
json.dumps(j)

那么你想更改為

j = {'trades': [trades]}

如果x是 Pandas dataframe 就像您描述的那樣:

   stopLoss  takeProfit    price  id
0    154.79      151.79  153.784   0
1    254.79      151.79  153.784   1

你可以試試

json.dumps(x.to_dict(orient='records'))    

這讓你幾乎到了那里:

[{"stopLoss": 154.79, "takeProfit": 151.79, "price": 153.784, "id": 0},
 {"stopLoss": 254.79, "takeProfit": 151.79, "price": 153.784, "id": 1}]

要獲得您需要的內容,只需創建一個字典:

json.dumps({ 'trades' : x.to_dict(orient='records') })

暫無
暫無

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

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