Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ adds single quotes while saving in environment variables

OK, this might be a silly question. I've got the test.json file:

{
    "timestamp": 1234567890,
    "report": "AgeReport"
}

What I want to do is to extract timestamp and report values and store them in some env variables:

export $(cat test.json | jq -r '@sh "TIMESTAMP=\(.timestamp) REPORT=\(.report)"')

and the result is:

echo $TIMESTAMP $REPORT
1234567890 'AgeReport'

The problem is that those single quotes break other commands. How can I get rid of those single quotes?

NOTE: I'm gonna leave the accepted answer as is, but see @Inian's answer for a better solution.

like image 599
Rad Avatar asked Sep 01 '25 15:09

Rad


1 Answers

Why make it convoluted with using eval and have a quoting mess? Rather simply emit the variables by joining them with NULL (\u0000) and read it back in the shell environment

{
  IFS= read -r -d '' TIMESTAMP 
  IFS= read -r -d '' REPORT
} < <(jq -r '(.timestamp|tostring) + "\u0000" + .report + "\u0000"' test.json)

This makes your parsing more robust by making the fields joined by NULL delimiter, which can't be part of your string sequence.

like image 116
Inian Avatar answered Sep 07 '25 14:09

Inian