jq

how to use jq to get value from key value dictionary in JSON


I need to get the username and email address for each user in the JSON below.

The tricky thing is that each property of the user is stored in a dictionary of name value pairs. The number of name-value pairs is not fixed and the order of the email address property is not fixed either.

{
  "Users": [
    {
      "Username": "test",
      "Attributes": [
        {
          "Name": "department",
          "Value": "department 1"
        },
        {
          "Name": "random attribute",
          "Value": "random attribute value"
        },
        {
          "Name": "email",
          "Value": "test@gmail.com"
        }
      ]
    },
    {
      "Username": "test2",
      "Attributes": [
        {
          "Name": "email",
          "Value": "test2@gmail.com"
        },
        {
          "Name": "department",
          "Value": "department 1"
        }
      ]
    }
  ]
}

I want to extract each user and their email address like so:

{
  "Username": "test",
  "email": "test@gmail.com"
},
{
  "Username": "test2",
  "email": "test2@gmail.com"
}

The closest I got was this convoluted line:

.Users[] | (.Attributes | map (contains ( {Name:"email", Value: "test@gmail.com"} )) | any(.))

which returns

true
false

Solution

  • You should first iterate over the Users array, form the JSON with Username and the Value field inside the Attributes array with key name as email. Then select the email field containing the @

    .Users[] | { Username, email : .Attributes[].Value } | select(.email | contains("@"))