HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

How can I pipe jq output

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
pipecanoutputhow

Problem

I recently learned about an outstanding little tool, jq that allows you to pipe unformatted JSON output into it and then have that output reformatted and output to the screen in a very nicely formatted color-coded json layout. Eg:

echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq


I have found however, that I am unable to pipe the formatted results (from jq) into additional tools in my standard toolset, such as grep, sed, awk, etc. How can I make make this output pipe-able? Eg, this doesn't work:

'{"value": "New", "onclick": "CreateNewDoc()"}' | jq | grep value

Solution

Ok tried to understand your problem exactly... This is what is happening:

$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq | grep value
jq - commandline JSON processor [version 1.5-1-a5b5cbe]
Usage: jq [options]  [file...]
[rest of output is omitted for brevity]


The important thing to notice here is the usage line (emphasis is mine):


Usage: jq [options] [file...]

The filter is not optional, if you don't give one, jq tries to parse the rest of the command line as its filter and throws an error. A workaround for your case here is:

$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq '.' | grep value
  "value": "New",


which indeed greps the "value" line as the filter passed is '.' - this just pretty prints the json content, but that's far from the best use of jq. If you wish to get only this line it would be better do:

$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq '.value'
"New"


If you wish to get the output without quotes then you can add add -r option to jq like so:

$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq -r '.value'
New


from jq --help:


-r output raw strings, not JSON texts;

that's a little introduction to jq, that's probably not enough to solve your problem at all but as you didn't specify your problem I can't help more than that.

Code Snippets

$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq | grep value
jq - commandline JSON processor [version 1.5-1-a5b5cbe]
Usage: jq [options] <jq filter> [file...]
[rest of output is omitted for brevity]
$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq '.' | grep value
  "value": "New",
$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq '.value'
"New"
$ echo '{"value": "New", "onclick": "CreateNewDoc()"}' | jq -r '.value'
New

Context

StackExchange DevOps Q#2928, answer score: 16

Revisions (0)

No revisions yet.