2

For example:

echo '{"p":2}{"q":3}' | jq '.'

How do I select the first object? I want the object below:

{"p":2}
3
  • 1
    @Inian - It's valid as a JSON stream, which I think it reasonable to assume is the OP's intent. Commented Nov 25, 2021 at 9:55
  • @peak: I wasn't sure of OP's expectation. Are they looking to get just {}, or it was a just a placeholder to contain some meaningful input inside Commented Nov 25, 2021 at 9:55
  • @inian - It makes no difference. {} is a valid JSON object. Commented Nov 25, 2021 at 10:00

1 Answer 1

3

You would use the -n command-line option, e.g.:

jq -n input

or

jq -n 'first(inputs)'
Sign up to request clarification or add additional context in comments.

5 Comments

echo '{"p":2}{"q":3}' | jq -n 'first(inputs)' works. Thank you.
If there are five objects and I wanted the 3rd, how would I do it?
To get the nth object (0-based) : echo '{"p":2}{"q":3}{"r":4}{"s":5}{"t":6}' | jq -n 'nth(2;inputs)' -> {"r":4}
echo '{"p":2}{"q":3}{"r":4}{"s":5}{"t":6}' | jq --slurp '.[2]' also works!
Re "jq --slurp '.[2]' also works", yeah, jq --slurp '...' is the same as jq -n '[ inputs ] | ...' These aren't as good as using first and nth as they require loading the entire stream into memory at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.