Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve the next key value pair in a json file with jq when I know the previous one

I have the following json file :

{
   "entry1":"",
   "entry2":"",
   "entry3":"value3",
   "entry4":"value4",
   "entry5":"",
   "entry6":" ",
   "entry7":"",
   "entry8":"false"
}

I know the key value pair of the entry3 but not the next one (entry4 and value)
How can I do ?

For now, I’m stuck on the below command :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jq -r 'to_entries[] | select(.value == "value3") | .key, .value'

>Solution :

You can use to_entries once more (acting on the array) in which case you get numbers as indices in the .key field. Do your filtering with select, then increment the result .key, and fetch that item by direct indexing .[n]:

to_entries | .[
  to_entries[] | select(.value.value == "value3").key + 1
] | .key, .value
entry4
value4

Demo

Note that the entries in JSON objects semantically don’t have an order, i.e. any other ordering would be considered the same object. to_entries merely returns the items in representation order, which is what you wanted to query, just be aware that this piece of information, strictly speaking, is not part of the data conveyed by the JSON input.


Edit:

My goal is to retrieve the key values pairs for entry3 and entry4

In this case, you could slide through the array returned by to_entries with a window of two overlapping items, e.g. using while(. != []; .[1:])[:2]. Then, select as before but from the first item in that window, and eventually output the data from the first and last item:

to_entries | while(. != []; .[1:])[:2]
| select(first.value == "value3")
| first.key, first.value, last.key, last.value
entry3
value3
entry4
value4

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading