jq: print key and value for each entry in an object

拜拜、爱过 提交于 2019-11-27 04:13:49

问题


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

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.


回答1:


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 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 and TSV output

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

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

produces:

host1   10.1.2.3
host2   10.1.2.2
host3   10.1.18.1



回答2:


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

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



来源:https://stackoverflow.com/questions/34226370/jq-print-key-and-value-for-each-entry-in-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!