jq:为对象中的每个条目打印键和值 [英] jq: print key and value for each entry in an object

查看:103
本文介绍了jq:为对象中的每个条目打印键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 jq 来获取json,如下所示:

How do I get jq to take json like this:

{
  "host1": { "ip": "10.1.2.3" },
  "host2": { "ip": "10.1.2.2" },
  "host3": { "ip": "10.1.18.1" }
}

并生成以下输出:

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.

推荐答案

要获取顶级密钥作为流,可以使用keys [].因此,针对您的特定问题的一种解决方案是:

To get the top-level keys as a stream, you can use keys[]. So one solution to your particular problem would be:

jq -r 'keys[] as $k | "\($k), \(.[$k] | .ip)"' 

keys按排序顺序生成键名;如果要按原始顺序使用它们,请使用keys_unsorted.

keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted.

另一种以原始顺序生成密钥的替代方法是:

Another alternative, which produces keys in the original order, is:

jq -r 'to_entries[] | "\(.key), \(.value | .ip)"'

CSV和TSV输出

例如@csv和@tsv过滤器在这里也可能值得考虑.

CSV and TSV output

The @csv and @tsv filters might also be worth considering here, e.g.

jq -r 'to_entries[] | [.key, .value.ip] | @tsv'

产生:

host1   10.1.2.3
host2   10.1.2.2
host3   10.1.18.1

这篇关于jq:为对象中的每个条目打印键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆