JQ: How to multiply values that are recognised as strings?

安稳与你 提交于 2020-01-13 19:24:06

问题


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.

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}

The commands below are followed by their outputs:

... | jq  '"\(.p*.q)"'
    jq: error (at <stdin>:1): string ("10796.6000...) and string ("0.00139000") cannot be multiplied

Then:

... | 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)"'

Or:

... | jq  '.q as $qtty | "\(.p|tonumber*"\($qtty|tonumber)")"'

It outputs too many numbers!

Even with the -r option, it does not work. I would expect just the raw result of multiplication to appear, like so:

15.0072740

回答1:


Keep it simple,

jq -r '(.p | tonumber)*(.q | tonumber)'


来源:https://stackoverflow.com/questions/56861281/jq-how-to-multiply-values-that-are-recognised-as-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!