How can I collect JSON node names using Groovy JSONpath?

2,979 views
Skip to first unread message

Pavel Furs

unread,
Sep 25, 2012, 8:30:20 AM9/25/12
to rest-a...@googlegroups.com
Hello,

I need to parse a JSON which looks like:
{
    "root": {
        "names": {
            "randomName1": {},
            "randomName2": {},
            "randomName3": {},
        }
    }
}
The goal is to collect element names into List<String>
According to http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlSlurper, the path expression should look like:

root.names.'*'.name()
or
root.names.'*'.collect{it.name()}

However I'm getting "java.lang.IllegalArgumentException: No signature of method: Script1.name() is applicable for argument types: () values: []" error while trying to use these expressions.

Could you please assist?
Thanks.

Johan Haleby

unread,
Sep 25, 2012, 9:23:02 AM9/25/12
to rest-a...@googlegroups.com
Hi,

Depth-first searching doesn't work (afaik) in Groovy with JSON documents unfortunately.

Here's what you can do:

List<String> list = from(json).getList("root.names*.getKey()", String.class);

Which will return [randomName3, randomName2, randomName1]. I don't know why the order is reversed but you can easily fix this (if order is important):

List<String> list = from(json).getList("root.names*.getKey().reverse()", String.class);

"*." means that for each element in the "root.names" list invoke method "getKey()". 

Regards,
/Johan

Pavel Furs

unread,
Sep 25, 2012, 11:38:54 AM9/25/12
to rest-a...@googlegroups.com
Thanks! It works fine.

Is there anywhere complete list of methods available for JSON?

Johan Haleby

unread,
Sep 25, 2012, 12:29:02 PM9/25/12
to rest-a...@googlegroups.com
Not that I know of. You can search for groovy collection tutorial or something like that. If you find a good reference please let us know.

/Johan
Reply all
Reply to author
Forward
0 new messages