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

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?