Printing multiple values on the same line

Mickster picture Mickster · Sep 9, 2017 · Viewed 12.9k times · Source

I'm trying to parse a JSON document and print a couple of values on the same line. Is there a way to take the following document:

{
  "fmep": {
    "foo": 112,
    "bar": 234324,
    "cat": 21343423
  }
}

And spit out:

112 234324

I can get the values I want but they are printed on separate lines:

$ echo '{ "fmep": { "foo": 112, "bar": 234324, "cat": 21343423 } }' | jq '.fmep|.foo,.bar'

112  
234324

If there is an example somewhere that shows how to do this I would appreciate any pointers.

Answer

jq170727 picture jq170727 · Sep 9, 2017

The easiest way in your example is to use String Interpolation along with the -r option. e.g.

echo '{ "fmep": { "foo": 112, "bar": 234324, "cat": 21343423 } }' | \
jq -r '.fmep| "\(.foo) \(.bar)"'

produces

112 234324

You may also want to consider putting the values in an array and using @tsv e.g.

echo '{ "fmep": { "foo": 112, "bar": 234324, "cat": 21343423 } }' | \
jq -r '.fmep | [.foo, .bar] | @tsv'

which produces tab-separated

112 234324