Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: error: test1/0 is not defined at <top-level>, line 1

Tags:

shell

jq

I have below JSON file and facing error when trying to add values to array dynamically in the shell.

Below is a tmp.json file,

{
  "environments": {
    "integration": [
      "testing for jenkins job"
    ],
    "prod": [],
    "staging": [],
    "uat": []
  }
}

When I try to append values to an array with a static variable, it works fine. Below is the command, jq '.environments.integration += ["test1"]' tmp.json

The respective output is,

{
  "environments": {
    "appbuild": [],
    "integration": [
      "testing for jenkins job",
      "test1"
    ],
    "prod": [],
    "staging": [],
    "uat": []
  }
 }

Whereas when I try to append values dynamically, it throws an error.

export Environment_Name="integration"
jq ".environments."\"${Environment_Name}"\" += test1" tmp.json

Error I am getting is,

jq: error: test1/0 is not defined at <top-level>, line 1:
.environments."integration" += test1
jq: 1 compile error

Can anyone please help to fix this.

like image 258
Gowthaman Javi Avatar asked Dec 07 '18 13:12

Gowthaman Javi


2 Answers

You have some extra quotes in there and test1 needs to be ["test1"]

jq ".environments.${Environment_Name} += [\"test1\"]" tmp.json

like image 116
Stefan Avatar answered Oct 16 '22 22:10

Stefan


Using shell-based variable interpolation is usually a very bad idea. In the present case, what if the shell variable contains a double-quotation mark, for example?

The safe thing to do is to use env or --arg or --argjson as appropriate, e.g.

jq --arg e "${Environment_Name}" '.environments[$e] += ["test1"]'
like image 19
peak Avatar answered Oct 16 '22 21:10

peak