jq reformatting decimals in scientific notation — can this be avoided?

前端 未结 3 2068
轻奢々
轻奢々 2020-12-19 05:23

I found difference between json-data created by JavaScipt and via jq with bash (and other programming languages). With JavaScript I can create decimal numbers w

相关标签:
3条回答
  • 2020-12-19 05:37

    A commit made on Oct 21, 2019, ensures that jq will generally preserve the "external" format of numbers. There are some exceptions, e.g. superfluous leading 0s.

    The following page gives details about installing an "unreleased" version of jq: https://github.com/stedolan/jq/wiki/Installation

    0 讨论(0)
  • 2020-12-19 05:46

    Also, you can reformat your JSON using perl module JSON::PP.

    perl -0777 -MJSON::PP -E '$s=<>; $j=JSON::PP->new->ascii->pretty->allow_nonref->allow_bignum;$p=$j->decode($s);say $j->encode($p)'
    

    or nicer:

    perl -0777 -MJSON::PP -E '
        $j=JSON::PP->new->ascii->pretty->allow_nonref->allow_bignum;
        $p=$j->decode(<>);
        say $j->encode($p)'
    

    The crucial is the allow_bignum.

    Example:

    echo '{"decimal":0.00000001}' | perl ....
    

    prints

    {
       "decimal" : 0.00000001
    }
    

    but without the allow_bignum prints

    {
       "decimal" : 1e-08
    }
    

    Ps: ... and also, is possible to validate the whole json using perl... :)

    0 讨论(0)
  • 2020-12-19 05:50

    You can't change jq's behavior -- at present date, relevant feature requests are still open -- but you can reformat your numbers after they've been retrieved. For example:

    json='{"decimal":0.00001}'
    decimal=$(jq '.decimal' <<<"$json")
    decimal_f=$(awk -v decimal="$decimal" 'BEGIN { printf("%f\n", decimal) }' </dev/null)
    
    echo "JQ emitted $decimal; reformatted as $decimal_f"
    
    0 讨论(0)
提交回复
热议问题