Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jq when the variable has reserved characters?

I'm trying to get the following to work and it's not, help me please:

curl -s 'https://cryptofresh.com/api/asset/markets?asset=MKR' | jq .OPEN.BTC

The variable in question includes a period, I tried just about everything to escape the period && also tried surrounding it in quotes; no go ; this is the variable I'm looking to pull from (I ran jq without any filters, and truncated the output here to show what I need. Thanks in advance future problem solver!

curl -s 'https://cryptofresh.com/api/asset/markets?asset=MKR' | jq
....
 "OPEN.BTC": {
"volume24": 0.932166,
"price": 0.09995,
"updated": "2016-05-04T03:03:29.000Z"
},
....
like image 513
Jonny Gerold Avatar asked May 04 '16 04:05

Jonny Gerold


People also ask

How do you remove quotes from jq output?

If you want to strip the quotes, just pipe the output from this command to tr -d '"' .

Does jq use JSONPath?

JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.

Can jq validate JSON?

jq – a lightweight and flexible CLI processor – can be used as a standalone tool to parse and validate JSON data.


2 Answers

When a key contains characters that are invalid for identifiers, you'll have to quote the name.

."OPEN.BTC"

Or for older versions of jq, use an index.

.["OPEN.BTC"]

Example

... | jq '."OPEN.BTC"'
like image 96
Jeff Mercado Avatar answered Oct 12 '22 21:10

Jeff Mercado


Another answer didn't work for me but the comment written by @jeff-mercado worked for me. So, adding it as an answer here.

If your key has dots like "OPEN.BTC" then your jq command should be

curl -s 'https://cryptofresh.com/api/asset/markets?asset=MKR' | jq '."OPEN.BTC"'

Put the key first in double quotes and then escape the first dot by wrapping it using single quotes.

like image 20
Kumaran Avatar answered Oct 12 '22 21:10

Kumaran