JQ:如何将被识别为字符串的值相乘? [英] JQ: How to multiply values that are recognised as strings?
问题描述
我正试图从交易所网络套接字获取一些贸易信息. 从套接字获取的JSON中,.p和.q值都用双引号引起来.
I am trying to get some trade information from an exchange websocket. Both values .p and .q are enclosed between double quotes in the JSON I get from the socket.
当我尝试将两个值相乘时,它表示我正在尝试将两个字符串相乘.因此,我通过tonumber过滤器传递了这些字符串,并且错误消息有所更改,但无法使其真正起作用.
When I try to multiply two values, it says I am trying to multiply two strings. So I pass those strings though the tonumber filter and the error message changes a bit, but can't get it to work really.
JSON:
{"e":"aggTrade","E":1562109562958,"s":"BTCUSDT","a":134343336,"p":"10796.60000000","q":"0.00139000","f":147532295,"l":147532295,"T":1562109562951,"m":false,"M":true}
下面的命令及其输出:
... | jq '"\(.p*.q)"'
jq: error (at <stdin>:1): string ("10796.6000...) and string ("0.00139000") cannot be multiplied
然后:
... | jq '"\(.p|tonumber*.q|tonumber)"'
jq: error (at <stdin>:1): Cannot index string with string "q"
... | jq '"\("\(.p|tonumber)"*"\(.q|tonumber)")"'
jq: error (at <stdin>:1): string ("10796.6") and string ("0.00139") cannot be multiplied
我得到的最接近的是下面的代码,但是它输出许多页面的结果,我只希望得到一个结果...
The closest I get is with the code below, but it outputs many pages of results and I only expect one result...
... | jq '.q as $qtty | "\(.p|tonumber*$qtty|tonumber)"'
或者:
... | jq '.q as $qtty | "\(.p|tonumber*"\($qtty|tonumber)")"'
它输出的数字太多!
即使使用-r选项,它也不起作用. 我希望只是乘法的原始结果会出现,就像这样:
Even with the -r option, it does not work. I would expect just the raw result of multiplication to appear, like so:
15.0072740
推荐答案
保持简单,
jq -r '(.p | tonumber)*(.q | tonumber)'
这篇关于JQ:如何将被识别为字符串的值相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!