Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq error syntax error, unexpected '=', expecting '}' (Unix shell quoting issues?) at <top-level>

cat test.json | jq 'map(if ParameterKey == "Project"           then . + {"ParameterValue" = "jess-project"}             else .             end           )'

jq: error: syntax error, unexpected '=', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
map(if ParameterKey == "Project"           then . + {"ParameterValue" = "jess-project"}             else .             end           )                                                                      
jq: 1 compile error
like image 848
spiderman Avatar asked Nov 17 '17 01:11

spiderman


2 Answers

Object construction in jq uses syntax similar to JavaScript Object Notation (JSON).

{"ParameterValue" = "jess-project"} is not valid in JSON. Did you mean {"ParameterValue": "jess-project"}?

like image 147
Jacob Krall Avatar answered Oct 14 '22 00:10

Jacob Krall


Ran into this after reading this here, and thought I add these notes, even if original post was so long ago. Hope it helps someone.

Aside from the incorrect use of = instead of : as pointed out above, I was also making the wrong assumption about the entire JSON object. So, make sure you're parsing that test.json correctly. For instance, if all ParameterKey/ParameterValues are in a list called Parameters and it looks something like this:

$ cat test.json
{
  "Parameters": [
    {
      "ParameterKey": "Project",
      "ParameterValue": "jess-project"
    },
    {
      "ParameterKey": "NumberOfInstances",
      "ParameterValue": "2"
    }
  ]
}

Then you have to take into account the Parameters list by doing:

$ jq '.Parameters | map(if .ParameterKey == "Project" then . + {"ParameterValue":"my-project"} else . end) | {"Parameters":.}' test.json
{
  "Parameters": [
    {
      "ParameterKey": "Project",
      "ParameterValue": "my-project"
    },
    {
      "ParameterKey": "NumberOfInstances",
      "ParameterValue": "2"
    }
  ]
}

Note that the list is added back at the end, by the last pipe.

By the way, here's another way to update a key's value:

$ jq '.Parameters | map((select(.ParameterKey == "Project") | .ParameterValue) |= "my-project") | {"Parameters":.}' test.json
{
  "Parameters": [
    {
      "ParameterKey": "Project",
      "ParameterValue": "my-project"
    },
    {
      "ParameterKey": "NumberOfInstances",
      "ParameterValue": "2"
    }
  ]
}

And if you want to specify a shell variable, you can even do this:

PRJ=my-project
jq --arg prj "$PRJ" '.Parameters | map((select(.ParameterKey == "Project") | .ParameterValue) |= $prj) | {"Parameters":.}' test.json > test-updated.json

In above example we're redirecting the modifications to new file test-updated.json, because invariably you'll most likely want to do that anyway since jq just doesn't have a replace-in-place option like sed -i.

like image 20
Paco Avatar answered Oct 14 '22 01:10

Paco