What is the jq equivalent for the slurp option?
Asked Answered
S

2

6

This generates a list of arrays:

$ echo -e "a 1\nb 2" | jq -R 'split(" ")'
[
  "a",
  "1"
]
[
  "b",
  "2"
]

When I slurp the input I get an array:

$ echo -e "a 1\nb 2" | jq -R 'split(" ")' | jq -s .
[
  [
    "a",
    "1"
  ],
  [
    "b",
    "2"
  ]
]

But when I try to convert the list into an array without slurping it, I get a list of arrays instead of a single array:

$ echo -e "a 1\nb 2" | jq -R '[split(" ")]'
[
  [
    "a",
    "1"
  ]
]
[
  [
    "b",
    "2"
  ]
]

Is it possible to slurp the result of the split without piping the result into a new instance of jq?

Stringendo answered 2/7, 2018 at 9:6 Comment(1)
C
5

Before the advent of inputs, the answer to the question was "No". With inputs and the -n command-line option:

$ echo -e "a 1\nb 2" | jq -nR '[inputs|split(" ")]' 
[
  [
    "a",
    "1"
  ],
  [
    "b",
    "2"
  ]
]
Cabbala answered 2/7, 2018 at 13:47 Comment(0)
D
-1

With double split:

echo -e "a 1\nb 2" | jq -sR 'split("\n")[:-1] | map(split(" "))'

The output:

[
  [
    "a",
    "1"
  ],
  [
    "b",
    "2"
  ]
]
Delafuente answered 2/7, 2018 at 9:23 Comment(1)
I know I can use the slurp option. But I was asking, if something equivalent exists as a jq expression.Stringendo

© 2022 - 2024 — McMap. All rights reserved.