[英]jq: print key and value for each entry in an object
How do I get jq to take json like this:我如何让jq像这样接受 json:
{
"host1": { "ip": "10.1.2.3" },
"host2": { "ip": "10.1.2.2" },
"host3": { "ip": "10.1.18.1" }
}
and generate this output:并生成此输出:
host1, 10.1.2.3
host2, 10.1.2.2
host3, 10.1.18.1
I'm not interested in the formatting, I just can't figure out how to access the key name and value.我对格式不感兴趣,我只是不知道如何访问键名和值。
To get the top-level keys as a stream, you can use the built-in function keys[]
.要将顶级键作为流获取,您可以使用内置功能
keys[]
。 So one solution to your particular problem would be:因此,您的特定问题的一种解决方案是:
jq -r 'keys[] as $k | "\($k), \(.[$k] | .ip)"'
keys
produces the key names in sorted order; keys
按排序顺序生成键名; if you want them in the original order, use keys_unsorted
.如果您希望它们按原始顺序排列,请使用
keys_unsorted
。
Another alternative, which produces keys in the original order, is:另一种按原始顺序生成密钥的替代方法是:
jq -r 'to_entries[] | "\(.key), \(.value | .ip)"'
The @csv and @tsv filters might also be worth considering here, eg @csv 和 @tsv 过滤器在这里也值得考虑,例如
jq -r 'to_entries[] | [.key, .value.ip] | @tsv'
produces:产生:
host1 10.1.2.3
host2 10.1.2.2
host3 10.1.18.1
If the keys of interest are embedded as in the following example, the jq filter would have to be modified along the lines shown.如果感兴趣的键如下例所示嵌入,则必须按照所示行修改 jq 过滤器。
Input:输入:
{
"myhosts": {
"host1": { "ip": "10.1.2.3" },
"host2": { "ip": "10.1.2.2" },
"host3": { "ip": "10.1.18.1" }
}
}
Modification:修改:
jq -r '.myhosts | keys[] as $k | "\($k), \(.[$k] | .ip)"'
Came across very elegant solution遇到了非常优雅的解决方案
jq 'with_entries(.value |= .ip)'
Which ouputs哪些输出
{
"host1": "10.1.2.3",
"host2": "10.1.2.2",
"host3": "10.1.18.1"
}
Here is the jqplay snippet to play with: https://jqplay.org/s/Jb_fnBveMQ这是要使用的 jqplay 片段: https ://jqplay.org/s/Jb_fnBveMQ
The function with_entries
converts each object in the list of objects to Key/Value-pair, thus we can access .key
or .value
respectively, we're updating (overwriting) every KV-item .value
with the field .ip
by using update |=
operator函数
with_entries
将对象列表中的每个对象转换为键/值对,因此我们可以分别访问.key
或.value
,我们使用 update 使用字段.ip
更新(覆盖)每个 KV-item .value
|=
运算符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.