JsonPath and root arrays

1,508 views
Skip to first unread message

Ludovic Orban

unread,
Jan 16, 2012, 1:10:18 PM1/16/12
to REST assured
Hi,

I have a set of REST services and they all return a single JSON array,
like this:

[{"prop1":"value1","prop2":"value2"}]

and I would like to write assertions like this:

.expect().body("[0].prop1", equalTo("value1"))

Unfortunately this throws an IllegalArgumentException as the
JSONAssertion.getAsJsonObject() groovy method hardcodes a '.' right
before the key which makes the JSON expression invalid.

So I've hacked the src/main/groovy/com/jayway/restassured/assertion/
JSONAssertion.groovy file and changed the getAsJsonObject method to
look like this instead:

def getAsJsonObject(object) {
key = escapePath(key, minus(), attributeGetter());
def result;
if (key == "\$" || key == "") {
result = object
} else {
def root = 'restAssuredJsonRootObject'
try {
def expr;
if (key.startsWith("[")) {
expr = "$root$key"
} else {
expr = "$root.$key"
}
result = Eval.me(root, object, expr)
} catch (Exception e) {
throw new
IllegalArgumentException(e.getMessage().replace("startup failed:",
"Invalid JSON expression:").replace("$root.",
generateWhitespace(root.length())));
}
}
return result
}

and then my above key example works. Would it be possible to include
those changes in the next rest-assured release?

Thanks!

Johan Haleby

unread,
Jan 16, 2012, 2:28:20 PM1/16/12
to rest-a...@googlegroups.com
Hi,

I did some minor changes and applied it to trunk so it'll be available
in the next release. Thanks for the tip. What you can do in the mean
time is to use the "get" method:

.expect().body("get(0).prop1", equalTo("value1"))

Regards,
/Johan

Reply all
Reply to author
Forward
0 new messages