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;








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?










share|improve this question






























    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?










    share|improve this question


























      0












      0








      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?










      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 27 at 13:55









      testtest

      578 bronze badges




      578 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          2














          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





          share|improve this answer






















          • 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





            @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





            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











          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
          );



          );













          draft saved

          draft discarded


















          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









          2














          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





          share|improve this answer






















          • 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





            @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





            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
















          2














          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





          share|improve this answer






















          • 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





            @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





            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














          2












          2








          2







          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





          share|improve this answer















          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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          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





            @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





            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





            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





            @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





            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









          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.



















          draft saved

          draft discarded
















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript