bashjq

How to add array from object's keys in jq


I want to add bundleDependencies from the dependencies's keys by using jq.

json_string="$(cat <<'END'
{
  "name": "hello",
  "dependencies": {
    "progress": "^2.0.0",
    "tar": "^6.2.1"
  }
}
END
)"

Here is the command for adding bundleDependencies but got error:

# jq ".bundleDependencies = (.dependencies | keys[])" <<< "$json_string")"
bash: syntax error near unexpected token `)'

Here is the expected output:

{
  "name": "hello",
  "dependencies": {
    "progress": "^2.0.0",
    "tar": "^6.2.1"
  },
  "bundleDependencies": ["progress", "tar"]
}

What's wrong in my jq command and how to fix?


Solution

  • Don't iterate over the keys, just take the array:

    .bundleDependencies = (.dependencies | keys)
    
    {
      "name": "hello",
      "dependencies": {
        "progress": "^2.0.0",
        "tar": "^6.2.1"
      },
      "bundleDependencies": [
        "progress",
        "tar"
      ]
    }
    

    Demo

    Note: keys sorts the array. Use keys_unsorted to prevent that.