How do I use JQ to flatten JSON-lines where each is an array into an item-per-line?

Viewed 72

I have the JSON as at bottom. If I send it to jq '.a[].b I get

[
  "x1",
  "x2"
]
[
  "y1",
  "y2"
]

How do I instead get line-by-line output, no brackets, quotes, or commas, like this:

x1
x2
y1
y2

The input JSON is:

{
  "a": [
    {
      "b": [
        "x1",
        "x2"
      ],
      "z": "z"
    },
    {
      "b": [
        "y1",
        "y2"
      ],
      "w": "w"
    }
  ]
}
2 Answers

Do the same thing with each b that you did with each a. Use the -r option to get the raw text, rather than JSON string values.

% jq -r '.a[].b[]' tmp.json
x1
x2
y1
y2

That is, .b outputs the list; .b[] outputs each element of the list.

With your shown samples, attempts you could try following jq code also. Using -r option of jq to send input in raw form. Then appropriately getting values as per requirement here.

jq -r '(.[] | .[].b)[]'  Input_file

Output will be as follows:

x1
x2
y1
y2
Related