Search code examples
jsonjsonpathjson-query

How to find all the json key-value pair by matching the value using json query


I have below JSON structure :

{
    "key" : "value",
    "array" : [
        { "key" : 1 },
        { "key" : 2, "misc": {
                "a": "Apple",
                "b": "Butterfly",
                "c": "Cat",
                "d": "Dog"
            } },
        { "key" : 3 }
    ],
    "tokenize" : {
         "firstkey" : {
                      "token" : 0
                    },
         "secondkey" : {
                      "token" : 1
                    },
         "thirdkey" : {
                      "token" : 0
                    }
      }

}

I am able to traverse the above structure till array->dictionary->b by the below syntax :

$.array[?(@.key=2)].misc.b

Now I need to print all the tokens which has value 0. The same way as shown above I can traverse till $.array[?(@.key=2)].tokenize.

How can I query it to print all values having token:0 .

To be very precise, I want the output to be shown as :

[

      "tokenize" : {
         "firstkey" : {
                      "token" : 0
                    },
         "thirdkey" : {
                          "token" : 0
                        }
          }
]

The following query already showing something near to what I want but it does not show the keys ("firstkey" and "thirdkey" in this case).

 $.tokenize[?(@.token == 0)]

Please help me to get this as well.

Thanks.


Solution

  • You can try this script.

    $.tokenize[?(@.token == 0)].token
    

    Result:

    [
        0,
        0
    ]