1

I want to use jq to pretty-print a JSON-format file, and pipe the result to another json file.

My first instinct was cat foo.json | jq > bar.json but this results in an empty bar.json:

$ cat << EOF > foo.json
> { "hello": "world" }
> EOF
$
$ cat foo.json | jq
{
  "hello": "world"
}
$
$ cat foo.json | jq > bar.json
jq - commandline JSON processor [version 1.5-1-a5b5cbe]
Usage: jq [options] <jq filter> [file...]
    jq is a tool for processing JSON inputs, applying the
    given filter to its JSON text inputs and producing the
    filter's results as JSON on standard output.
    The simplest filter is ., which is the identity filter,
    copying jq's input to its output unmodified (except for
    formatting).
    For more advanced filters see the jq(1) manpage (&quot;man jq&quot;)
    and/or https://stedolan.github.io/jq

    Some of the options include:
     -c             compact instead of pretty-printed output;
     -n             use `null` as the single input value;
     -e             set the exit status code based on the output;
     -s             read (slurp) all inputs into an array; apply filter to it;
     -r             output raw strings, not JSON texts;
     -R             read raw strings, not JSON texts;
     -C             colorize JSON;
     -M             monochrome (don't colorize JSON);
     -S             sort keys of objects on output;
     --tab  use tabs for indentation;
     --arg a v      set variable $a to value &lt;v&gt;;
     --argjson a v  set variable $a to JSON value &lt;v&gt;;
     --slurpfile a f        set variable $a to an array of JSON texts read from &lt;f&gt;;
    See the manpage for more options.

$ cat bar.json $

cat foo.json | jq works as expected: the pretty-printed json gets output to stdout.

What is going wrong with cat foo.json | jq > bar.json? Why doesn't the stdout of cat foo.json | jq get redirected to file?

If there's nothing fundamentally wrong with what I'm trying to do, what is the correct way to achieve it?


Update: genius ChatGPT said I should do jq < foo.json > bar.json, but the result is identical to above, i.e. jq < foo.json appears functionally fine, but jq < foo.json > bar.json results in an empty bar.json.

StoneThrow
  • 1,717
  • 4
    You're using an old version of jq. You need to use either jq . when the output is not to a TTY, or upgrade to jq 1.6 – muru Oct 12 '23 at 00:41

0 Answers0