Search code examples
javarestpostrest-assuredrest-assured-jsonpath

How to find key from value in rest assured java?


I am using rest assured java and i am using post request in order to get the response. From my code i am able to get the response and i am seeing that in response i am seeing that value which i want to store is present in the keyset. Here is the example:

{
    "status_code": 200,
    "status_message": "OK",
    "response": {
        "applications": {
            "345": "A",
            "125": "B",
            "458": "C",
            "434": "D",
            "512": "E",
            "645": "F"
        }
    }
}

In the above example i am using Json path to parse through the expression and i want to use Value "A" extract the key("345") from it.

JsonPath js = new JsonPath(res);
String Key  = js.get("response.applications.A");

when i am using above code it throws an error but when i run the below code.

JsonPath js = new JsonPath(res);
String Key  = js.get("response.applications.345");

I get the output as A. I know what is [A,b,c,d,e,f] but i don't know what is Key for [A,b,c,d,e,f]

Is there any way where i can store the value and prints the key for that value in rest assured or any other way in Java?????


Solution

  • Using JsonPath, you can get the keys by calling getMap. Here is an example of how you would go about doing this:

    String jsonString = "{\"status_code\": 200,\"status_message\": \"OK\",\"response\":{\"applications\":{\"345\": \"A\",\"125\": \"B\",\"458\": \"C\",\"434\": \"D\",\"512\": \"E\",\"645\": \"F\"}}}";
    JsonPath jsonPath = new JsonPath(jsonString);
    Map<String, String> applicationsMap = jsonPath.getMap("response.applications");
    Set<String> applicationKeys = applicationsMap.keySet();
    for(String key:applicationKeys){
        System.out.println("Key value: " + key + ", Element value: " + applicationsMap.get(key));
    }
    

    Hope this helps!