Shadi
Shadi

Reputation: 10335

How to pass a variable to jq when the json is in a file?

I'm trying to recreate this SO question but with storing the json in a file instead of passing the string on the command line. Here's what I'm doing:

$ cat test.json 
{"number":$number}

$ jq --arg number 3000 test.json 
jq: error: test/0 is not defined at <top-level>, line 1:
test.json
jq: 1 compile error

What am I doing wrong?

Upvotes: 2

Views: 1082

Answers (2)

hek2mgl
hek2mgl

Reputation: 157927

Like this:

# That's not json, it's a .jq file
cat test.jq
{"number":$number}

jq -n --arg number 3000 -f test.jq
{
  "number": "3000"
}

Btw, the above example gives you "3000" as a string. If you want it to be a number you need to use --argjson:

jq -n --argjson number 3000 -f test.jq
{
  "number": 3000
}

or as a string

jq -n --argjson number '"3000"' -f test.jq
{
  "number": "3000"
}

Upvotes: 4

Bertrand Martel
Bertrand Martel

Reputation: 45352

You don't need to use jq here if you use environment variables and substitute them with envsubst like this :

export number=3000
envsubst < test.json

Upvotes: 1

Related Questions