Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

json - jq reformatting decimals in scientific notation -- can this be avoided?

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 with up to six digits after the point, even when I use float(). But with jq its different, because adding a decimal value takes four digits after the decimal point only.

My problem is that I need decimal numbers to store in SQL, with up to six digits after the point.

Example:

$ JSON='{"decimal":0.00001}'
$ echo "$JSON" | jq .
{
  "decimal": 1e-05
}

My goal is to validate the decimal with this line ...

if [[ "$TMP_DECIMAL" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then

Any tip / suggsestion ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", decimal) }' </dev/null)

echo "JQ emitted $decimal; reformatted as $decimal_f"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...