jq - Print leading and trailing context surrounding each match?Converting JSON data to Java objectGoogle Gson - deserialize list<class> object? (generic type)PHP “pretty print” json_encodeJavascript object Vs JSONjson_encode sparse PHP array as JSON array, not JSON objectDisplaying better error message than “No JSON object could be decoded”Select objects based on value of variable in object using jqProper way to return JSON using node or ExpressPrint each array in objectHow can i match fields with wildcards using jq?
What exactly happened to the 18 crew members who were reported as "missing" in "Q Who"?
What is bodily formation? Does it refer to the breath or the body?
Quick destruction of a helium filled airship?
Why should P.I be willing to write strong LOR even if that means losing a undergraduate from his/her lab?
Why should I pay for an SSL certificate?
Why don't modern jet engines use forced exhaust mixing?
My new Acer Aspire 7 doesn't have a Legacy Boot option, what can I do to get it?
Repurpose telephone line to ethernet
!I!n!s!e!r!t! !b!e!t!w!e!e!n!
Is there a commercial liquid with refractive index greater than n=2?
Earliest evidence of objects intended for future archaeologists?
Why do balloons get cold when they deflate?
Why doesn't mathematics collapse down, even though humans quite often make mistakes in their proofs?
Inset Square From a Rectangular Face
Polar contour plot in Mathematica?
Atmospheric methane to carbon
Adding things to bunches of things vs multiplication
Sinc interpolation in spatial domain
What should I do with the stock I own if I anticipate there will be a recession?
Do living authors still get paid royalties for their old work?
9 hrs long transit in DEL
Best model for precedence constraints within scheduling problem
Is "stainless" a bulk or a surface property of stainless steel?
From France west coast to Portugal via ship?
jq - Print leading and trailing context surrounding each match?
Converting JSON data to Java objectGoogle Gson - deserialize list<class> object? (generic type)PHP “pretty print” json_encodeJavascript object Vs JSONjson_encode sparse PHP array as JSON array, not JSON objectDisplaying better error message than “No JSON object could be decoded”Select objects based on value of variable in object using jqProper way to return JSON using node or ExpressPrint each array in objectHow can i match fields with wildcards using jq?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
Is it possible to print the leading & trailing context of a match in jq
?
Say i have the following JSON:
...
[
"message": "Validating...",
,
"message": "Validated.",
,
"message": "Saving...",
,
"message": "Saved.",
]
...
I want to be able to match a string where message=="Validating..."
, then get the the next n
trailing or leading objects from the match.
With grep
, you have the -C
option to get the context. Is there anything similar in jq
?
json jq
add a comment |
Is it possible to print the leading & trailing context of a match in jq
?
Say i have the following JSON:
...
[
"message": "Validating...",
,
"message": "Validated.",
,
"message": "Saving...",
,
"message": "Saved.",
]
...
I want to be able to match a string where message=="Validating..."
, then get the the next n
trailing or leading objects from the match.
With grep
, you have the -C
option to get the context. Is there anything similar in jq
?
json jq
add a comment |
Is it possible to print the leading & trailing context of a match in jq
?
Say i have the following JSON:
...
[
"message": "Validating...",
,
"message": "Validated.",
,
"message": "Saving...",
,
"message": "Saved.",
]
...
I want to be able to match a string where message=="Validating..."
, then get the the next n
trailing or leading objects from the match.
With grep
, you have the -C
option to get the context. Is there anything similar in jq
?
json jq
Is it possible to print the leading & trailing context of a match in jq
?
Say i have the following JSON:
...
[
"message": "Validating...",
,
"message": "Validated.",
,
"message": "Saving...",
,
"message": "Saved.",
]
...
I want to be able to match a string where message=="Validating..."
, then get the the next n
trailing or leading objects from the match.
With grep
, you have the -C
option to get the context. Is there anything similar in jq
?
json jq
json jq
asked Mar 27 at 13:55
testtest
578 bronze badges
578 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
If objects under the array contain only one key-value pair each, use index
to get the index of matching one:
index(message:"Validating")
Otherwise:
map(.message == "Validating...")|index(true)
Or use this more efficient function:
def find(condition):
label $out
| foreach .[] as $p (-1; . + 1
if $p | condition
then ., break $out
else empty end);
Then use this index for slicing the array:
# all leading
.[0:find(.message == "Validating...")]
# all trailing
.[find(.message == "Validating..."):]
# leading three
find(.message == "Validating...") as $i | .[if $i < 3 then 0 else $i - 3 end:$i]
# trailing three
find(.message == "Validating...") as $i | .[$k:$k + 4]
# etc
1
wow, thank you!
– test
Mar 27 at 14:34
You need to use$k - 3:$k+1
&$k:$k + 4
, the end indice is exclusive
– Aaron
Mar 27 at 14:37
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction
– Aaron
Mar 27 at 14:40
1
@oguzismailecho '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns[6]
when you would want it to return[1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6
– Aaron
Mar 27 at 14:48
2
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)
– Aaron
Mar 27 at 15:03
|
show 1 more comment
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55378978%2fjq-print-leading-and-trailing-context-surrounding-each-match%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
If objects under the array contain only one key-value pair each, use index
to get the index of matching one:
index(message:"Validating")
Otherwise:
map(.message == "Validating...")|index(true)
Or use this more efficient function:
def find(condition):
label $out
| foreach .[] as $p (-1; . + 1
if $p | condition
then ., break $out
else empty end);
Then use this index for slicing the array:
# all leading
.[0:find(.message == "Validating...")]
# all trailing
.[find(.message == "Validating..."):]
# leading three
find(.message == "Validating...") as $i | .[if $i < 3 then 0 else $i - 3 end:$i]
# trailing three
find(.message == "Validating...") as $i | .[$k:$k + 4]
# etc
1
wow, thank you!
– test
Mar 27 at 14:34
You need to use$k - 3:$k+1
&$k:$k + 4
, the end indice is exclusive
– Aaron
Mar 27 at 14:37
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction
– Aaron
Mar 27 at 14:40
1
@oguzismailecho '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns[6]
when you would want it to return[1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6
– Aaron
Mar 27 at 14:48
2
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)
– Aaron
Mar 27 at 15:03
|
show 1 more comment
If objects under the array contain only one key-value pair each, use index
to get the index of matching one:
index(message:"Validating")
Otherwise:
map(.message == "Validating...")|index(true)
Or use this more efficient function:
def find(condition):
label $out
| foreach .[] as $p (-1; . + 1
if $p | condition
then ., break $out
else empty end);
Then use this index for slicing the array:
# all leading
.[0:find(.message == "Validating...")]
# all trailing
.[find(.message == "Validating..."):]
# leading three
find(.message == "Validating...") as $i | .[if $i < 3 then 0 else $i - 3 end:$i]
# trailing three
find(.message == "Validating...") as $i | .[$k:$k + 4]
# etc
1
wow, thank you!
– test
Mar 27 at 14:34
You need to use$k - 3:$k+1
&$k:$k + 4
, the end indice is exclusive
– Aaron
Mar 27 at 14:37
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction
– Aaron
Mar 27 at 14:40
1
@oguzismailecho '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns[6]
when you would want it to return[1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6
– Aaron
Mar 27 at 14:48
2
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)
– Aaron
Mar 27 at 15:03
|
show 1 more comment
If objects under the array contain only one key-value pair each, use index
to get the index of matching one:
index(message:"Validating")
Otherwise:
map(.message == "Validating...")|index(true)
Or use this more efficient function:
def find(condition):
label $out
| foreach .[] as $p (-1; . + 1
if $p | condition
then ., break $out
else empty end);
Then use this index for slicing the array:
# all leading
.[0:find(.message == "Validating...")]
# all trailing
.[find(.message == "Validating..."):]
# leading three
find(.message == "Validating...") as $i | .[if $i < 3 then 0 else $i - 3 end:$i]
# trailing three
find(.message == "Validating...") as $i | .[$k:$k + 4]
# etc
If objects under the array contain only one key-value pair each, use index
to get the index of matching one:
index(message:"Validating")
Otherwise:
map(.message == "Validating...")|index(true)
Or use this more efficient function:
def find(condition):
label $out
| foreach .[] as $p (-1; . + 1
if $p | condition
then ., break $out
else empty end);
Then use this index for slicing the array:
# all leading
.[0:find(.message == "Validating...")]
# all trailing
.[find(.message == "Validating..."):]
# leading three
find(.message == "Validating...") as $i | .[if $i < 3 then 0 else $i - 3 end:$i]
# trailing three
find(.message == "Validating...") as $i | .[$k:$k + 4]
# etc
edited Mar 28 at 6:53
answered Mar 27 at 14:15
oguz ismailoguz ismail
10.5k7 gold badges15 silver badges35 bronze badges
10.5k7 gold badges15 silver badges35 bronze badges
1
wow, thank you!
– test
Mar 27 at 14:34
You need to use$k - 3:$k+1
&$k:$k + 4
, the end indice is exclusive
– Aaron
Mar 27 at 14:37
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction
– Aaron
Mar 27 at 14:40
1
@oguzismailecho '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns[6]
when you would want it to return[1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6
– Aaron
Mar 27 at 14:48
2
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)
– Aaron
Mar 27 at 15:03
|
show 1 more comment
1
wow, thank you!
– test
Mar 27 at 14:34
You need to use$k - 3:$k+1
&$k:$k + 4
, the end indice is exclusive
– Aaron
Mar 27 at 14:37
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction
– Aaron
Mar 27 at 14:40
1
@oguzismailecho '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns[6]
when you would want it to return[1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6
– Aaron
Mar 27 at 14:48
2
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)
– Aaron
Mar 27 at 15:03
1
1
wow, thank you!
– test
Mar 27 at 14:34
wow, thank you!
– test
Mar 27 at 14:34
You need to use
$k - 3:$k+1
& $k:$k + 4
, the end indice is exclusive– Aaron
Mar 27 at 14:37
You need to use
$k - 3:$k+1
& $k:$k + 4
, the end indice is exclusive– Aaron
Mar 27 at 14:37
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),
.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction– Aaron
Mar 27 at 14:40
Ah, more problematic : if the start index gets in the negative, it slices from the end of the array, which will lead to an empty result. If the relevant functions are available (see here),
.[fmin($k-3,0):$k+4]
should give you a window centered on the target element with at most 3 additional elements in each direction– Aaron
Mar 27 at 14:40
1
1
@oguzismail
echo '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns [6]
when you would want it to return [1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6– Aaron
Mar 27 at 14:48
@oguzismail
echo '[1,2,3,4,5,6]' | jq '2 as $k | .[$k-3:$k+4]'
returns [6]
when you would want it to return [1,2,3,4,5]
; that's because the slice between -1 and 6 is the slice between 5 and 6– Aaron
Mar 27 at 14:48
2
2
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using
.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)– Aaron
Mar 27 at 15:03
When you're slicing the array, you need to be careful your start index doesn't get into the negatives, or you start indexing from the end of the array. Here you can see an example of that problem with your code. I propose using
.[([0, $k-3]|max):$k+4]
as slice to get the target object and the 3 object before and after when they exist (edit : yeah, that works too !)– Aaron
Mar 27 at 15:03
|
show 1 more comment
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55378978%2fjq-print-leading-and-trailing-context-surrounding-each-match%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown