jsonbashjq

How to add and combine objects in jq


I want to use jq to add new objects into the following JSON string.

Here is the test json_string:

json_string="$(cat <<'END'
{
  "hello": {
    "foo": {
      "version": "1.1.1"
    }
  },
  "world": {
    "bar": {
      "version": "2.2.2"
    }
  }
}
END
)"

Here is the hello:

# hello="$(jq -r ".hello" <<< "$json_string")"
# echo "$hello"
{
  "foo": {
    "version": "1.1.1"
  }
}

Here is the world:

# world="$(jq -r ".world" <<< "$json_string")"
# echo "$world"
{
  "bar": {
    "version": "2.2.2"
  }
}

Here is the full JSON string including the newly added combined:

# full="$(jq -r ".+= combined ${hello} ${world}" <<< "$json_string")"
jq: error: syntax error, unexpected '{', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.+= combined {             
jq: 1 compile error

Here is the expected full JSON:

# echo "$full"
{
  "hello": {
    "foo": {
      "version": "1.1.1"
    }
  },
  "world": {
    "bar": {
      "version": "2.2.2"
    }
  }
  "combined": {
    "foo": {
      "version": "1.1.1"
    },
    "bar": {
      "version": "2.2.2"
    }
  }
}

How to generate the "full" JSON with jq?


Solution

  • There is no need for those extra 2 steps/variables, you can achieve the expected output with 1 JQ call like so:

    jq '.combined = .hello + .world' <<< "$json_string"
    

    But if you define world and hello as seperate variabels, you can pass those objects back to jq with --argjson and combine them in a new key:

    jq \
      --argjson hello "$hello" \
      --argjson world "$world" \
      '.combined = $hello + $world' <<< "$json_string"