Search code examples
javarest-assuredrest-assured-jsonpath

Using rest-assured get value using path method


I want to extract value of s.d.url from the below JSON.
I am using the below satement as shown using System.out.println but I dont get the result. How do I do it when the field itself contains "."

JSON

{  
   "data":{  
      "H1":{  
         "com.abc.def":{  
            "a_enabled":false,
            "b_config":true
         },
         "c.s.urls":{  
            "s.d.url":"https://url1.com",
            "w.p.url":"https://url2.com",
            "s.c.url":"https://url3.com"
         },
         "com.abc.con":{  
            "e_n":true,
            "a_r":false,
            "c_t":"XYZMB"
         }
      },
      "dCId":"ABCD"
   }
}

ExtractableResponse<Response> spec =  given()
    .request().log().all()
    .expect().statusCode(200)
    .when()
    .get(EndpointsCloudServices.getConfigUrl() + "?" + params)
    .then().log().body()
            .extract();

            //want to get value of s.d.url
            System.out.println("Triage????  " + spec.path("data.H1.c.s.urls.s.d.url"));

Solution

  • Give a try for the following, it will return value of s.d.url (pay attention for square brackets and single quotes):

    spec.path("data.H1.['c.s.urls'].['s.d.url']")

    or even shorter, if you're sure that s.d.url is an unique name across the whole json document:

    spec.path("$.['s.d.url']")

    And next, this is just to illustrate common case of referring field which contains dots in its name by using JSONPath expression - all you need is to wrap the field name in [' and ']

    Example JSON:

    {
       "field.name": "value",
       "nested": {
            "field.with.dot": {
                 "field.inside": "anotherValue"
            }
        }  
    }
    

    Example valid JSONPath expressions to access corresponding field values:

    $['field.name']                                 
    $.['field.inside']                            
    nested.['field.with.dot'].['field.inside']
    

    Hint: you can quickly test your JSONPaths agains your json using tools like online evaluator or expression tester