0

Related to: Getting data from json using jq when key is numerical string but different as I have the numerical key stored in a variable. See the example below.

File temp.json:

{
  "bccc26321e360ae5fde94aac81eef7c7270bbfd90de0787d0e5b45be4b21ce53": {
    "size": 189,
    "fee": 0.00000678,
    "modifiedfee": 0.00000678,
    "time": 1535906461,
    "height": 539665
  },
  "43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e": {
    "size": 256,
    "fee": 0.00008328,
    "modifiedfee": 0.00008328,
    "time": 1535906461,
    "height": 539665
  }
}

Attempts to index with a variable:

#get second key 43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e
>txid=$(cat temp.json | jq 'keys' | jq .[1] | tr -d '"')
>cat temp.json | jq .$txid
jq: error: syntax error, unexpected IDENT, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e
jq: 1 compile error

>cat temp.json | jq '.$txid'
q: error: syntax error, unexpected '$' (Unix shell quoting issues?) at <top-level>, line 1:
.$txid 
jq: error: try .["field"] instead of .field for unusually named fields at <top-level>, line 1:
.$txid
jq: 2 compile errors

>cat temp.json | jq '."$txid"'
null

The desired output is simply

>cat temp.json | jq '."43906c7227610cd58a1c95714e4f79cd46e0d98ae3f4214f1b2cf325b628b70e"'
{
        "size": 256,
        "fee": 0.00008328,
        "modifiedfee": 0.00008328,
        "time": 1535906461,
        "height": 539665
      }
4
  • If you want the quotes around the key, why do you delete them via tr? With what you have, I'd expect ".\"$txid\"" to work; if you drop the tr -d '"', ".$txid" may be enough. Commented Sep 2, 2018 at 17:53
  • it solved my problem, thanks Commented Sep 2, 2018 at 18:40
  • Have added it as an answer; would appreciate it if you could accept it. Commented Sep 2, 2018 at 19:53
  • BTW, better to run jq ... temp.json or jq ... <temp.json or <temp.json jq ... than cat temp.json | jq ... -- running cat means jq has to read from a FIFO from a separate program (cat) which has access to the file, instead of giving jq access to the input file directly. Commented Sep 2, 2018 at 23:23

1 Answer 1

1

If what you want is ."xxx" as argument, then use ".\"$txid\"". If you drop the tr -d '"', ".$txid" may even be enough.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.