How to Add a Key-Value Pair to a JSON File with JQ

jqjson

I have the following JSON file located at /tmp/target.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    ...
  }
}

I want to add a new key value pair so it will be as follows:

{
  "compileOnSave": false,
  "compilerOptions": {
    "skipLibCheck": true,
    "baseUrl": "./",
    ...
  }
}

I use the following command but it doesn't work:

jq --argjson addobj '{"skipLibCheck": "true"}' '
  .compilerOptions{} |= $addobj
' /tmp/target.json

I gives me this error:

jq: error: syntax error, unexpected '{', expecting $end (Unix shell quoting issues?) at <top-level>, line 2:
  .compilerOptions{} |= $addobj                  
jq: 1 compile error

What have I done wrong? How can I get it to work as intended?

Best Answer

Like this:

$ jq '.compilerOptions.skipLibCheck=true' file.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "skipLibCheck": true
  }
}
Related Question