50

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Mickster
  • 643
  • 2
  • 9
  • 13

3 Answers3

79

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
Carl Walsh
  • 6,100
  • 2
  • 46
  • 50
jq170727
  • 13,159
  • 3
  • 46
  • 56
  • 1
    That works like a charm! It looks like the jq "-j" option works as well but string interpolation is more readable. – Mickster Sep 10 '17 at 13:23
  • Maybe its just me, but doing TSV-conversion feels like doing it badly. Using string interpolation feels the natural way of outputting data. – Jari Turkia Nov 25 '21 at 07:53
14

Here is the syntax using joined output (-j):

jq -j '.fmep | .foo, " ", .bar, "\n"' payload.json
kenorb
  • 155,785
  • 88
  • 678
  • 743
6

Let's say our JSON (example.json) looks like this: { "hello":"world", "foo":"bar" }

In order to join a few fields into the same line you can:

$ jq -j '.hello,.foo' example.json

This will result in

worldbar

Want to add a delimiter? let's say a space

$ jq -j '.hello," ",.foo' example.json

This will result in

world bar

*Just make sure you are using jq version 1.5 or higher

RoyalBigMack
  • 620
  • 7
  • 7