简体   繁体   English

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

[英]Extract a specific field from JSON output using jq

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"]'我试过cat json_file | jq '.["example.sub-example.name"]' 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(或其他方法)来实现这一目标?

If you just want to extract the name fields, the command you're looking for is jq '.example."sub-example" | .[] | .name'如果您只想提取name字段,您要查找的命令是jq '.example."sub-example" | .[] | .name' jq '.example."sub-example" | .[] | .name' jq '.example."sub-example" | .[] | .name' . jq '.example."sub-example" | .[] | .name' If you want to keep the names in an array, wrap the whole jq expression in square brackets.如果要将名称保留在数组中,请将整个jq表达式括在方括号中。

In jq 1.3, you can use the filter to extract the values:在 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。

Reading into shell variables读入shell变量

Rather than populating separate shell variables (which would require knowing in advance how many values there are), consider populating a shell array.与其填充单独的 shell 变量(这需要事先知道有多少个值),不如考虑填充一个 shell 数组。 For example, using a bash shell with mapfile (aka readarray ):例如,使用带有mapfile (又名readarray )的 bash shell:

mapfile -t ary < <(< json_file jq '.example."sub-example"[].name')

You could alternatively use a shell while loop.您也可以使用 shell while循环。 Etc etc. There are many SO Qs on this topic.等等等等。关于这个话题有很多 SO Q。

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.您还可以使用map()来提取特定字段。 eg例如

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM