skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. A straightforward approach:

    to_entries
    | range(0;length-1) as $n
    | select( .[$n].key == "entry3" )
    | .[$n:$n+2][]
    | [.key, .value]
    

    This produces

    ["entry3","value3"]
    ["entry4","value4"]
    

    Tweak to taste.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search