简体   繁体   中英

How do I use jq to output a decimal low in linux

Given the following jq command and Json: (Only jq command)

echo '{"foo": {"bar": 0.00000072}}' | jq 'map_values( . + {"bar": .bar|tostring} )'
{
  "foo": {
    "bar": "7.2e-07"
  }
}

I'm trying to format the output as:

{
  "foo": {
    "bar": "0.00000072"
  }
}

OR

{
  "foo": {
    "bar": 0.00000072
  }
}

You could use this generic function:

def to_decimal:
  def rpad(n): if (n > length) then . + ((n - length) * "0") else . end;
  def lpad(n): if (n > length) then ((n - length) * "0") + . else . end;
  tostring
  | . as $s
  | capture( "(?<sgn>[+-]?)(?<left>[0-9]*)(?<p>\\.?)(?<right>[0-9]*)(?<e>[Ee]?)(?<exp>[+-]?[0-9]+)" )
  | if .e == "" then $s
    else (.left|length) as $len
    | (.exp | tonumber) as $exp
    | if $exp < 0 then .sgn + "0." + (.left | lpad(1 - $exp - $len)) + .right
      else .sgn + (.left | rpad($exp - $len)) + "." + .right
      end
    end ;

Example:

"7.2e-07"|to_decimal

yields:

"0.00000072"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM