Json
在 json 數據中,如何使用 jq 將整數轉換為美元金額?
我有這樣的數據
{ "dateCreated": "2020-06-12", "status": "pending", "depositDate": "2020-06-15", "amount": 41237 } { "dateCreated": "2020-06-05", "status": "paid", "depositDate": "2020-06-08", "amount": 37839 } { "dateCreated": "2020-04-02", "status": "paid", "depositDate": "2020-04-03", "amount": 67 }
它的格式
jq
如下:request-some-api | jq '.data[] | {dateCreated: .created | strftime("%Y-%m-%d"), status: .status, depositDate: .arrival_date | strftime("%Y-%m-%d"), amount: .amount,}'
我想修改它,
.amount
以便它顯示值而不是美分數作為帶小數位的美元金額……{ "dateCreated": "2020-06-12", "status": "pending", "depositDate": "2020-06-15", "amount": $412.37 } { "dateCreated": "2020-06-05", "status": "paid", "depositDate": "2020-06-08", "amount": $378.39 } { "dateCreated": "2020-04-02", "status": "paid", "depositDate": "2020-04-03", "amount": $.67 }
…但我還沒有找到任何關於此的文件?是否
jq
能夠進行這種轉換?即使沒有$
符號,只是添加.
美元和美分之間的數字也會有所幫助。
像這樣:
jq '.amount = "$" + (.amount/100|tostring)' file.json
輸出
{ "dateCreated": "2020-06-12", "status": "pending", "depositDate": "2020-06-15", "amount": "$412.37" } { "dateCreated": "2020-06-05", "status": "paid", "depositDate": "2020-06-08", "amount": "$378.39" } { "dateCreated": "2020-04-02", "status": "paid", "depositDate": "2020-04-03", "amount": "$0.67" }
您所需的輸出看起來格式不正確;我希望“金額”成為一個字元串值。
您可以通過在開頭添加 $ 來做到這一點,然後將金額除以 100 並轉換為字元串
例如
jq '.amount = "$" + (.amount/100|tostring)'
在您的測試文件上執行此操作,我們可以看到 3
amount
行轉換為:"amount": "$412.37" "amount": "$378.39" "amount": "$0.67"
然而,這有幾個奇怪的情況,這可能(或可能不)重要。如果金額以零結尾(例如 41230),那麼它將顯示為“ $ 412.3". Similarly if it’s whole dollars (41200) then it’ll display was " $ 412"。
我不確定
jq
有一個簡單的方法來處理這些,所以我添加了幾個測試:jq '.amount = "$" + (.amount/100|tostring) + (if .amount%100 == 0 then ".0" else "" end ) + (if .amount%10 ==0 then "0" else "" end)'
可能有更有效的方法。