使用 jq 从 JSON 输出中提取特定字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39228500/
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:35:11  来源:igfitidea点击:

Extract a specific field from JSON output using jq

jsonjq

提问by rmb

I have a JSON output as follows:

我有一个 JSON 输出如下:

{
  "example": {
    "sub-example": [
      {
        "name": "123-345",
        "tag" : 100
      },
      {
        "name": "234-456",
        "tag" : 100
      },
      {
        "name": "4a7-a07a5",
        "tag" : 100
      }
    ]
  }
}

I want to extract the values of the three "name" fields and store it in three variables.

我想提取三个“名称”字段的值并将其存储在三个变量中。

I tried cat json_file | jq '.["example.sub-example.name"]'to extract the value of the "name" field but that doesn't work.

我试图cat json_file | jq '.["example.sub-example.name"]'提取“名称”字段的值,但这不起作用。

Can anyone tell me how to achieve this using jq (or some other method)?

谁能告诉我如何使用 jq(或其他方法)来实现这一目标?

回答by aaaaaa123456789

If you just want to extract the namefields, the command you're looking for is jq '.example."sub-example" | .[] | .name'. If you want to keep the names in an array, wrap the whole jqexpression in square brackets.

如果您只想提取name字段,则您要查找的命令是jq '.example."sub-example" | .[] | .name'. 如果要将名称保留在数组中,请将整个jq表达式括在方括号中。

回答by peak

In jq 1.3, you can use the filter:

在 jq 1.3 中,您可以使用过滤器:

.example["sub-example"] | .[] | .name

Or more compactly:

或更紧凑:

.example["sub-example"][].name

These of course also work with later versions of jq as well.

这些当然也适用于更高版本的 jq。

回答by Mandar Pathak

It's been a few years and I recently had to do this myself so thought I should post another way here.

已经有几年了,我最近不得不自己做这件事,所以我想我应该在这里发布另一种方式。

You can also use map()to extract specific fields. e.g.

您还可以使用map()提取特定字段。例如

.example."sub-example"|map(.name)

Ref: https://jqplay.org/s/N6TboUkELM

参考:https: //jqplay.org/s/N6TboUkELM