【问题标题】:JQ: How to multiply values that are recognised as strings?JQ:如何将被识别为字符串的值相乘?
【发布时间】:2019-07-02 23:49:15
【问题描述】:

我正在尝试从交易所 websocket 获取一些交易信息。 .p 和 .q 这两个值都包含在我从套接字获取的 JSON 中的双引号之间。

当我尝试将两个值相乘时,它表示我正在尝试将两个字符串相乘。所以我通过 tonumber 过滤器传递了这些字符串,错误消息发生了一些变化,但不能让它真正工作。

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

我得到的最接近的是下面的代码,但它输出了很多页的结果,我只期望一个结果......

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

或者:

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

输出的数字太多了!

即使使用 -r 选项,它也不起作用。 我希望只出现乘法的原始结果,如下所示:

15.0072740

【问题讨论】:

    标签: json bash jq multiplication string-substitution


    【解决方案1】:

    保持简单,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2016-09-13
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多