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 :
jq -r 'to_entries[] | select(.value == "value3") | .key, .value'
2
Answers
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 withselect
, then increment the result.key
, and fetch that item by direct indexing.[n]
: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:
In this case, you could slide through the array returned by
to_entries
with a window of two overlapping items, e.g. usingwhile(. != []; .[1:])[:2]
. Then,select
as before but from thefirst
item in that window, and eventually output the data from thefirst
andlast
item:Demo
A straightforward approach:
This produces
Tweak to taste.