2

I have file.json in the structure of:

{
  "connections": {}
}

I want to update the connections object with variables $1 and $2. I'm trying:

jq --arg ssid "$1" --arg pass "$2" '.connections.$ssid = "$pass"' file.json > tmp.json && mv tmp.json file.json

But I'm getting back jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1: .connections.$ssid = "$pass"

I'm expecting script.sh value key to produce:

{
  "connections": {key:"value"}
}

How can I update the object with multiple arguments

4

You have to use [] indexing to use variables (or anything non-literal) as the key:

jq --arg ssid abc --arg pass 123 '.connections[$ssid] = $pass' < file.json
{
  "connections": {
    "abc": "123"
  }
}

Here [$ssid] indexes into .connections with the value of $ssid as the key. The error was at ".$", which is a syntax error, rather than to do with multiple variables.

Variables aren't substituted in directly as strings in the way they might be in a shell script, but are actual named lexical bindings that have to be used in expression context. The index could be a more complex expression: .connections[$ssid + "X"] = $pass would put an X on the end first and use that as the key.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.