json jq:打印对象中每个条目的键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34226370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:10:54  来源:igfitidea点击:

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

jsonobjectkeyexport-to-csvjq

提问by Jeff Tang

How do I get jqto 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.

我对格式不感兴趣,我只是不知道如何访问键名和值。

回答by peak

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

要将顶级键作为流获取,您可以使用内置函数keys[]。因此,您的特定问题的一种解决方案是:

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

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

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

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

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

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

CSV and TSV output

CSV 和 TSV 输出

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

@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

Embedded objects

嵌入对象

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)"'

回答by Viacheslav

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_entriesconverts each object in the list of objects to Key/Value-pair, thus we can access .keyor .valuerespectively, we're updating (overwriting) every KV-item .valuewith the field .ipby using update |=operator

该函数with_entries将对象列表中的每个对象转换为键/值对,因此我们可以访问.key.value分别使用更新运算符更新(覆盖).value具有字段.ip的每个 KV 项|=