jq - 如何使用 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
解决方案
您应该首先遍历 Users 数组,使用 Username 形成 JSON,并在 Attributes 数组中使用键名为 email 的 Value 字段。然后选择包含@
.Users[] | { Username, email : .Attributes[].Value } | select(.email | contains("@"))
推荐阅读
- ruby-on-rails - 修复 ruby 中的重复方法
- python - 寻找 k 个 clique 社区的有效算法
- architecture - 重用基础软件工程和组件基础软件工程之间的区别?
- visual-studio-2017 - 使用 SQL Server 2017 和 Visual Studio 2017 的常用 python 库
- microsoft-teams - 禁用用户后,他/她在 Microsoft Teams 中的消息会被删除吗?
- c++ - 这些问题都暗示着同样的事情吗?
- javascript - 在 Nodejs 和 Express 中使用 JQuery 需要帮助
- css - 我的 html.erb 视图页面内的内联 css 样式的背景图像仅在开发中显示,但在 heroku 上不显示生产阶段
- react-native - 标题空白和 ImageBackground
- apache-kafka-streams - kafka 流中的聚合和状态存储保留