使用 jq 根据哈希中的键选择对象
我很想根据哈希中的键选择对象,但我希望恢复原始对象格式。我怎样才能实现这个目标?
原始
{
"google.com": {
"http": {
"dest_url": "http://stackoverflow.com"
},
"https": {
"dest_url": "http://github.com"
}
},
"aaa.com": {
"https": {
"dest_url": "https://github.com"
}
},
"bbb.com": {
"https": {
"dest_url": "https://microsoft.com"
}
},
"ccc.com": {
"https": {
"dest_url": "https://.com"
}
}
}
应该是
{
"google.com": {
"http": {
"dest_url": "http://stackoverflow.com"
},
"https": {
"dest_url": "http://github.com"
}
},
"bbb.com": {
"https": {
"dest_url": "https://microsoft.com"
}
}
}
我用 to_entries[] | 尝试过它选择 (.key == "google.com" 或 .key == "bbb.com") | [.key, .value]
但它是这样的。我确信 [.key, .value]
部分是错误的,但我一直不知道如何解决这个问题。
[
"google.com",
{
"http": {
"dest_url": "http://stackoverflow.com"
},
"https": {
"dest_url": "http://github.com"
}
}
]
[
"bbb.com",
{
"https": {
"dest_url": "https://microsoft.com"
}
}
]
I'd love to select objects based on the key in the hash, but I want the original object format back. How can I achieve this?
original
{
"google.com": {
"http": {
"dest_url": "http://stackoverflow.com"
},
"https": {
"dest_url": "http://github.com"
}
},
"aaa.com": {
"https": {
"dest_url": "https://github.com"
}
},
"bbb.com": {
"https": {
"dest_url": "https://microsoft.com"
}
},
"ccc.com": {
"https": {
"dest_url": "https://.com"
}
}
}
should be
{
"google.com": {
"http": {
"dest_url": "http://stackoverflow.com"
},
"https": {
"dest_url": "http://github.com"
}
},
"bbb.com": {
"https": {
"dest_url": "https://microsoft.com"
}
}
}
I tried it with to_entries[] | select (.key == "google.com" or .key == "bbb.com") | [.key, .value]
but it eneded like this. I'm sure [.key, .value]
part is wrong but I'm stuck on how I can workaround this.
[
"google.com",
{
"http": {
"dest_url": "http://stackoverflow.com"
},
"https": {
"dest_url": "http://github.com"
}
}
]
[
"bbb.com",
{
"https": {
"dest_url": "https://microsoft.com"
}
}
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
with_entries(…)
,这是to_entries | 的快捷方式。地图(…)| from_entries
,它又将对象分解为键/值表示数组to_entries
,修改该数组map
中的每个项目,并将其转换回原始结构from_entries
。演示
Use
with_entries(…)
, which is a shortcut toto_entries | map(…) | from_entries
, which in turn decomposes the object into an array of key/value representationsto_entries
, modifies each item within that arraymap
, and converts it back into the original structurefrom_entries
.Demo