1

I have some JSON objects that I need to add a value to if it doesn't already exist.

Each object will be the following except the contact_group inside each array (1-5) will vary:

{
"contact_groups": {
    "1": [
      "/contact_group/78"
    ],
    "2": [
      "/contact_group/79"
    ],
    "3": [],
    "4": [],
    "5": []
  }
}

I would like to add "/contact_group/109" to each array if it doesn't already exist, so the above would become:

{
"contact_groups": {
    "1": [
      "/contact_group/78",
      "/contact_group/109"
    ],
    "2": [
      "/contact_group/79",
      "/contact_group/109"
    ],
    "3": [
      "/contact_group/109"
    ],
    "4": [
      "/contact_group/109"
    ],
    "5": [
      "/contact_group/109"
    ]
  }
}

I'm pretty sure jq can do this but I'm really inexperienced with it so I don't know where to begin. Does anyone know how/if this can be done?

1 Answer 1

2

You can use with_entries() function on the parent element to convert the sub elements into a pair keyed by key and value and add the string to value array, if it doesn't have it already

jq '.contact_groups |= ( with_entries( if ( .value | index("/contact_group/109") | not ) then .value += [ "/contact_group/109" ] else . end ) )'

The with_entries(..) builtin is a shorthand for doing to_entries | map | from_entries. The index("/contact_group/109") | not part ensures to add the entry if the string is not already present in the .value array.

See demo on jqplay

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .