Search code examples
bashmacoszshjq

jq produces `is not defined at <top-level>` error


I'm seeing a is not defined at <top-level> when calling jq like so:

jq ".Changes[0].ResourceRecordSet.Name = word-is-here.domain.com" someFile.json

The error repeats for each word separated by a dash in the second side of the replacement. The full error is like

jq: error: word/0 is not defined at <top-level>, line 1:
.Changes[0].ResourceRecordSet.Name = word-is-here.domain.com

I've tried escaping quotes in many different ways but that didn't help. (what I mean by this is doing "'"'" weird stuff, I'm still learning bash so I'm just trowing stuff at the wall until it sticks)

EDIT: So I'm trying to run this in a bash script, and both side of the = signs are variables such as jq --arg value "$value" --arg key "$key" '$key = $value' "$path" (what I tried after a suggestion)

and got the error: Invalid path expression with result ".Changes[0].ResourceRecor...

The json I'm using is as such:

{
  "Changes": [
    {
      "Action": "do something",
      "ResourceRecordSet": {
        "Name": "some name here to replace",
         ...
      }
    }
  ]
}

Solution

  • jq '.Changes[0].ResourceRecordSet.Name = "word-is-here.domain.com"' file.json
    

    Quote the string you are assigning. Or pass it to jq via an argument:

    jq --arg foo 'words-here' '.Changes[0].ResourceRecordSet.Name = $foo' file.json
    

    For passing the path to the key you want as an argument, a suggestion from https://github.com/stedolan/jq/issues/1493 might work:

    jq --argjson path '["Changes",0,"ResourceRecordSet","Name"]' \
      --arg val 'word-is-here.domain.com' \
      'getpath($path) = $val' file.json