[jq] Set a value at a path with setpath

Created on November 30, 2026

Pass an array of object keys and array indexes to setpath(path; value). This makes it possible to represent a field's location as data. In this example, index 1 selects the second element of users.

printf '%s\n' '{"users":[{"name":"Taro"},{"name":"Hanako"}]}' |
  jq 'setpath(["users",1,"name"]; "Sakura")'
{
  "users": [
    {
      "name": "Taro"
    },
    {
      "name": "Sakura"
    }
  ]
}

Use strings for keys and numbers for zero-based indexes. The second argument is the value to write at that position.

Create missing levels

If the keys in a path are absent, setpath can create the objects needed to set the value.

printf '%s\n' '{}' | jq 'setpath(["settings","theme"]; "dark")'
{
  "settings": {
    "theme": "dark"
  }
}

Here jq creates settings and writes dark to theme inside it.

Reference

jq