within json data, how to transform integer to dollar amount using jq?

Like this:

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

Output

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

Your required output looks malformed; I'd expect "amount" to become a string value.

You can do this by adding a $ to the beginning, then dividing the amount by 100 and converting to a string

eg

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

Doing that on your test file we can see the 3 amount lines get converted to:

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

However this has a couple of odd cases, which may (or may not) matter. If the amount ends in zero (eg 41230) then it will display as "$412.3". Similarly if it's whole dollars (41200) then it'll display was "$412".

I'm not sure jq has a simple way of handling these so I added a couple of tests:

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

There may be a more efficient way.


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

This converts the amount key's value to a string after dividing it by 100. It then trims off the leading zero if present before prepending a $ to the string.

Tags:

Json

Jq