Extract a specific field from JSON output using jq

JsonJq

Json Problem Overview


I have a JSON output as follows:

{
  "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.

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

Json Solutions


Solution 1 - Json

If you just want to extract the name fields, 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 jq expression in square brackets.

Solution 2 - Json

In jq 1.3, you can use the filter to extract the values:

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

Or more compactly:

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

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

Reading into shell variables

Rather than populating separate shell variables (which would require knowing in advance how many values there are), consider populating a shell array. For example, using a bash shell with mapfile (aka readarray):

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

You could alternatively use a shell while loop. Etc etc. There are many SO Qs on this topic.

Solution 3 - Json

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.

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrmbView Question on Stackoverflow
Solution 1 - Jsonaaaaaa123456789View Answer on Stackoverflow
Solution 2 - JsonpeakView Answer on Stackoverflow
Solution 3 - JsonMandar PathakView Answer on Stackoverflow