Home > database >  Jq Convert multiple string inputs to one larger array without slurp or inputs
Jq Convert multiple string inputs to one larger array without slurp or inputs

Time:05-02

I have:

Filter:

["key:\(.key)", "value:\(.value)"][]

Input:

{"key":"state","value":"pending"}
{"key":"options","value":"request"}

Output:

"key:state"
"value:pending"
"key:options"
"value:request"

Demo

https://jqplay.org/s/9yq89orzL0

I want to convert the output "key:state" "value:pending" "key:options" "value:request" to array ["key:state", "value:pending", "key:options", "value:request"].

I tried reduce . as $s ([]; . [$s]) but this gives ["key:state"] ["value:pending"] ["key:options"] ["value:request"].

I want a solution without using slurp or inputs.

Thanks.

CodePudding user response:

I want a solution without using slurp or inputs.

Unfortunately, unless you’re willing to invoke jq twice, those are the only two options that jq has to offer. And the same can be said of gojq and jaq.

If your input is JSONL (one JSON per line), then there are of course many obvious ways to preprocess the stream to achieve the "slurping" effect. Otherwise, you'd probably want to use a JSON-oriented tool, either to supplement jq, or to use instead.

CodePudding user response:

I wouldn't consider this a very practical solution but you could switch the scope from the itemwise stream to an enveloping singleton by using a second call to jq, and an appropriate encoding for the transition, thus using -j and -R to write and read a single line of raw text. Technically, this fulfills your requirements (not using slurp or inputs), but is it worth it?

One such way could be to manually build a JSON array from already JSON-encoded parts by adding commas and brackets:

In the first instance, encode the items as JSON using tojson, and append a comma to each. In the second instance, remove the last character (the superfluous comma), wrap the string in brackets, and decode the ready JSON array using fromjson.

jq -j '"key:\(.key)", "value:\(.value)" | "\(tojson),"' | jq -R '"[\(.[:-1])]" | fromjson'
[
  "key:state",
  "value:pending",
  "key:options",
  "value:request"
]

CodePudding user response:

If you can use --null-input and input :

#!/usr/bin/env bash 
  
jq --null-input '
def loop:
    . (input|["key:\(.key)", "value:\(.value)"]) |
    . as $res |
    try loop catch $res ;
loop
' << EOF
{"key":"state","value":"pending"}
{"key":"options","value":"request"}
EOF

output:

[
  "key:state",
  "value:pending",
  "key:options",
  "value:request"
]
  • Related