2

I'm sure this is very simple, but I do not know how to do it with jq.

I have a JSON like this one

[
  {
    "id": "109",
    "name": "aaa"
  },
  {
    "id": "1098",
    "name": [
      "bbb",
      "ccc"
    ]
  },
  {
    "id": "2000",
    "name": [
      "fff",
      "ddd"
    ]
  }
]

And I would like to extract the .name. When name is an array, I would like to take always the first element.

Do I must create an if clause, or is there some more direct mode?

As output I would like to have "aaa" "bbb" "fff", but I have "aaa" "bbb" "fff" "bbb" "fff".

Here is what I have so far:

if .[].name|type == "array" then .[].name[0]?  else first(.[].name) end

Output:

"aaa"
"bbb"
"fff"
"bbb"
"fff"

Interactive example https://jqplay.org/s/fOBuwdj6WS

peak
  • 105,803
  • 17
  • 152
  • 177
aborruso
  • 4,938
  • 3
  • 23
  • 40

1 Answers1

2

To extract all names, but only the first name in case the name is an array:

jq '.[].name | if type=="array" then first else . end' <file

For your sample input, the output is:

"aaa"
"bbb"
"fff"
randomir
  • 17,989
  • 1
  • 40
  • 55