简体   繁体   English

linux下如何使用jq输出小数点

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

Given the following jq command and Json: (Only jq command)给定以下 jq 命令和 Json:(仅 jq 命令)

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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