130

Say I have the input:

{
    "name": "John",
    "email": "[email protected]"
}
{
    "name": "Brad",
    "email": "[email protected]"
}

How do I get the output:

[
    {
        "name": "John",
        "email": "[email protected]"
    },
    {
        "name": "Brad",
        "email": "[email protected]"
    }
]

I tried both:

jq '[. | {name, email}]'

and

jq '. | [{name, email}]'

which both gave me the output

[
    {
        "name": "John",
        "email": "[email protected]"
    }
]
[
    {
        "name": "Brad",
        "email": "[email protected]"
    }
]

I also saw no options for an array output in the documentations, any help appreciated

3
  • How do I give a name to the new array instead of it being an anonymous array? So { "people": [ { "name": "Brad", "email": "[email protected]" } ]} Commented Jan 24, 2017 at 16:33
  • @user372429 you would just wrap the {people: } around your output, so it should look something like: jq -s '{people: . }' < tmp.json Commented Jan 26, 2017 at 15:31
  • 25
    try jq [.[] | {name,email}] Commented Nov 24, 2021 at 17:37

1 Answer 1

184

Use slurp mode:

  o   --slurp/-s:

      Instead of running the filter for each JSON object
      in the input, read the entire input stream into a large
      array and run the filter just once.
$ jq -s '.' < tmp.json
[
  {
    "name": "John",
    "email": "[email protected]"
  },
  {
    "name": "Brad",
    "email": "[email protected]"
  }
]
Sign up to request clarification or add additional context in comments.

9 Comments

You can also pipe initial jq results into jq -s if you need to. I.E ... | jq '.foo[].bar' | jq -s
I like adding another pipe to reduce steps in each command, but don't forget the '.' ... | jq '.foo[].bar' | jq -s '.'
@Adam jq assumes a filter of . if its standard output is a terminal.
You can just wrap the filter in [...] instead of running jq a second time; ... | jq '[.foo[].bar]'.
@chepner, I was piping into further commands, so the default didn't kick in for me. Sorry, I'd thought you had missed that last part.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.