在json数据中,如何使用jq将整数转换为美元金额?

在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做这样的转换吗?即使没有$符号,但只需添加.美元和美分之间的数字也会有所帮助。

答案1

像这样:

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"
}

答案2

您所需的输出看起来格式错误;我希望“金额”成为一个字符串值。

您可以通过在开头添加 $,然后将金额除以 100 并转换为字符串来完成此操作

例如

jq '.amount = "$" + (.amount/100|tostring)'

在您的测试文件上执行此操作,我们可以看到 3amount行已转换为:

"amount": "$412.37"
"amount": "$378.39"
"amount": "$0.67"

然而,这有一些奇怪的情况,这可能(也可能不重要)。如果金额以零结尾(例如 41230),则它将显示为“$412.3”。同样,如果是整数 (41200),那么它会显示“$412”。

我不确定jq是否有简单的方法来处理这些问题,因此我添加了一些测试:

jq '.amount = "$" + (.amount/100|tostring) + (if .amount%100 == 0 then ".0" else "" end ) + (if .amount%10 ==0 then "0" else "" end)'

可能有更有效的方法。

答案3

$ jq '.amount |= "$" + (./100 | tostring | ltrimstr("0"))' file
{
  "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"
}

这会将amount键的值除以 100 后将其转换为字符串。然后,在将 a 前置$到字符串之前,它会修剪掉前导零(如果存在)。

相关内容