i have a big json file
for example
{"id":"abc","data":"test1"}
{"id":"wer","data":"test2"}
{"id":"trg","data":"test3"}
....
i used this command for extract specific value filed As follows:
cat sample.json |jq 'if .id == "wer" then .data else empty end '
but jq search continues to end big json file and not exit.
Now my question is: how to exit jq after first matching
You could use the -n option together with 'inputs' and 'first', along the lines of:
first( inputs | ... )
thanks for answer.
other question. how to extract nth object from mentoined big json file above ?
for example how to get 123th object from json file
thanks
You basically have a collection of objects, all peers, not related to each other. If you load them with jq -s, it will wrap them in an array, and you could then select the 123th object like so:
cat sample.json | jq -s '.[122]'
(the first one being [0], of course...)
Aside from indexing them within a containing array or object, I don't know of a way to isolate just the one you want.
@s3c1t - Again with the -n option: nth(122; items)
That avoids the need to use -s
very thanks for answers.
when i used this commands
cat sample.json | jq -s '.[122]'
due to used huge json file. usage cpu above 90 percent and very be slowed my linux
@s3c1t, did you try:
jq -n 'nth(122;inputs)' <sample.json
That works for me, and is tremendously faster than the -s .[122] version.
thanks for answers.
how to exit jq proccessing json file when find first match.
in the other word
terminating jq processing when condition is met
for example i used this commands
echo -e '{"id":1,"data":"test"}\n{"id":2,"data":"test2"}\n{"id":3,"data":"test3"}\n{"id":1,"data":"test4"}' |jq 'if .id == 1 then . else empty end'
output:
{
"data": "test",
"id": 1
}
{
"data": "test4",
"id": 1
}
but i don't want this output
i want when first match then exit proccessing json file this means
output:
{
"data": "test",
"id": 1
}
in the other word
I am using jq to search for specific results in a large file. I do not care for duplicate entries matching this specific condition, and it takes a while to process the whole file. What I would like to do is print some details about the first match and then terminate the jq command on the file to save time.
I.e.
jq '. | if ... then "print something; exit jq" else ... end'
+1 on the "find first"/"find one" functionality
@arnm There is.
In OP's case the thing to do is jq -n 'first( inputs | ... )'. The first/1 builtin does what its name implies.
@s3c1t The first/1 approach works for terminating early in your case. In master there's a halt builtin.