skip to Main Content

I’m having an hard time trying to grok jq for good.
I want to change the result from list to array. Now this question was already addressed on these SO questions that say to just put brackets arount the query:

Output the results of select operation in an array – jq

JQ: How to turn output of array selector back into an array?

What I want is basically the same but it’s not working. I have a file with three lines:

me 
you
them

now with this command line: cat list | jq -R '.' The result is:

"me"
"you"
"them"

ok now I want to convert to array, so as in the questions I should only put some brackets in the identity filter. If I do this (cat list | jq -R '[.]') I get:

[
  "me"
]
[
  "you"
]
[
  "them"
]

??? WHYYYY ? If I try cat list | jq -R '.[]' the result is:

jq: error (at <stdin>:1): Cannot iterate over string ("me")
jq: error (at <stdin>:2): Cannot iterate over string ("you")
jq: error (at <stdin>:3): Cannot iterate over string ("them")

how do I get

[
    "me",
    "you",
    "them"
]

? I don’t want to use inputs function. I want to be able to use in the simple cat whatever | jq 'whatever' format.
The worst thing is that it works for a complex query on a big JSON but not for that simple case. What am I doing wrong ?

Edit

I found a way to do it, but I don’t consider this an answer because I really think there should be a better way, please enlighten me on how I could do this better.

cat list | jq -sR 'split("n") | map(select(length > 0))'

then I finally got the desired

[
    "me",
    "you",
    "them"
]

without map I got another (empty) string in the array due to the last n

Ugly as hell and I still don’t know why I got the results I mentioned above. To me cat list | jq -R '[.]') should have worked.

2

Answers


  1. The succinct solution is the one you disallow:

    jq -Rn '[inputs]'
    

    Next best without using split would be:

    jq -R . list | jq -s .
    

    Depending on which version of jq you use, you might also be able to use a variant such as:

     cat list | jq -R | jq -s
    
    Login or Signup to reply.
  2. I believe the problem comes in with jq trying to parse the input as JSON on some level (even though -R is being passed)

    If the input can be quoted, jq does output it correctly with a simple filter, i.e

    awk '{print """$0"""}' list  | jq -s '.'
    

    or

    cat list | jq -R '.' | jq -s '.'
    

    both work given the original input.

    The following works, provided you can quote the inputs e.g

    "me"
    "you"
    "them"
    
    cat list2 | jq -s '.'
    

    returns:

    [
      "me",
      "you",
      "them"
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search