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

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현