0

I have a JSON that looks like:

{
  "LDAP": {
    "RemoteRoleMapping": [
      {
        "LocalRole": "dirgroup234fe3432",
        "RemoteGroup": "CN=somethingelse,OU=another,OU=more,DC=my,DC=org"
      },
      {
        "LocalRole": "dirgroup47829ab78ed33",
        "RemoteGroup": "CN=mememe,OU=another,OU=more,DC=my,DC=org"
      },
      {
        "LocalRole": "dirgroup94728afe32a",
        "RemoteGroup": "CN=sysadmin,OU=another,OU=more,DC=my,DC=org"
      }
    ]
  }
}

I need to modify the DN of one of the Remote Group names. What I did was:

TMPF=$(mktemp)
NEWDN="CN=something,OU=another,OU=more,DC=my,DC=org"
DATA="<above JSON>"
echo ${DATA} | jq -r '.[] | select(.RemoteGroup="'${OLDDN}'") | .RemoteGroup = "'${NEWDN}'"' | jq --slurp '.' > ${TMPF}
DATA=$(echo '{"LDAP":{"RemoteRoleing": '$(cat ${TMPF})'}}' | jq -r '.')

which gets my a DATA variable with the correct group name. My question is about the line with the slurp in it. Is there a better way to do this jq?

1 Answers1

0

You can use the --arg option to pass data into jq variables, and update the field in passing:

echo "$DATA" \
| jq  --arg newdn "this is the new DN" \
      --arg olddn "CN=sysadmin,OU=another,OU=more,DC=my,DC=org" \
      '.LDAP.RemoteRoleMapping |= map(
          if .RemoteGroup == $olddn
          then .RemoteGroup = $newdn
          else .
          end)'

outputs this, with the last RemoteGroup changed

{
  "LDAP": {
    "RemoteRoleMapping": [
      {
        "LocalRole": "dirgroup234fe3432",
        "RemoteGroup": "CN=somethingelse,OU=another,OU=more,DC=my,DC=org"
      },
      {
        "LocalRole": "dirgroup47829ab78ed33",
        "RemoteGroup": "CN=mememe,OU=another,OU=more,DC=my,DC=org"
      },
      {
        "LocalRole": "dirgroup94728afe32a",
        "RemoteGroup": "this is the new DN"
      }
    ]
  }
}
glenn jackman
  • 27,524