3

When I use commmand:

jq -r '.balances[] | select(.asset=="BTC").free' wallet.json

result: "4723846.89208129"

When I use command:

coin2=BTC    
jq -r '.balances[] | select(.asset=="$coin2").free' wallet.json

result: nothing

How to fix this error? Help me please!

wallet.json here:

{
  "makerCommission": 15,
  "takerCommission": 15,
  "buyerCommission": 0,
  "sellerCommission": 0,
  "canTrade": true,
  "canWithdraw": true,
  "canDeposit": true,
  "updateTime": 123456789,
  "accountType": "SPOT",
  "balances": [
    {
      "asset": "BTC",
      "free": "4723846.89208129",
      "locked": "0.00000000"
    },
    {
      "asset": "LTC",
      "free": "4763368.68006011",
      "locked": "0.00000000"
    }
  ],
  "permissions": [
    "SPOT"
  ]
}
NamPT
  • 41

1 Answers1

4
  • First, pass that variable value to jq with --arg coin2 "$coin2" first like so:

    jq -r --arg coin2 "$coin2" '.balances[] | select(.asset==$coin2).free' wallet.json
    
  • Second, don't quote that passed variable $coin2 inside the jq command string ' ... ' or otherwise it will be read literally as a fixed string instead of being expanded to its value.

From man jq:

--arg name value:

This option passes a value to the jq program as a predefined variable. If you run jq with --arg foo bar, then $foo is available in the program and has the value "bar". Note that value will be treated as a string, so --arg foo 123 will bind $foo to "123".

Raffa
  • 32,237