首页 > 解决方案 > 如何使用 jq 从 JSON 中的键值字典中获取值

问题描述

我需要在下面的 JSON 中获取每个用户的用户名和电子邮件地址。

棘手的是用户的每个属性都存储在名称值对的字典中。名称-值对的数量不固定,电子邮件地址属性的顺序也不固定。

{
  "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"
        }
      ]
    }
  ]
}

我想像这样提取每个用户及其电子邮件地址:

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

我得到的最接近的是这条复杂的线:

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

返回

true
false

标签: jq

解决方案


您应该首先遍历 Users 数组,使用 Username 形成 JSON,并在 Attributes 数组中使用键名为 email 的 Value 字段。然后选择包含@

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

推荐阅读