简体   繁体   中英

How to get keyset from a string in groovy?

I have a following String in Groovy:

[[{"qunit":{"total":0,"passed":0,"failed":0,"skipped":0}}], [{"utest": {"total":0,"passed":0,"failed":0,"skipped":0}}]]

I need to get just the keys 'qunit' and 'utest'

How is it possible?

You can parse that JSON string and then read the list:

def p = new JsonSlurper()
def list = 
    p.parseText("""[[{"qunit":{"total":0,"passed":0,"failed":0,"skipped":0}}], 
                   [{"utest": {"total":0,"passed":0,"failed":0,"skipped":0}}]]""")

def keys = list.flatten().collect{it.keySet()}.flatten()

Result is [qunit, utest]

This obviously is specific to the layout of the input.

Your string represents a JSON document, so you need to use JsonSlurper first to parse it:

import groovy.json.JsonSlurper

final String json = '[[{"qunit":{"total":0,"passed":0,"failed":0,"skipped":0}}], [{"utest": {"total":0,"passed":0,"failed":0,"skipped":0}}]]'

def list = new JsonSlurper().parseText(json)

If you print list variable you will see something like this:

[[[qunit:[total:0, passed:0, failed:0, skipped:0]]], [[utest:[total:0, passed:0, failed:0, skipped:0]]]]

Firstly, we would need to flatten the list:

list.flatten()

which returns a list like:

[[qunit:[total:0, passed:0, failed:0, skipped:0]], [utest:[total:0, passed:0, failed:0, skipped:0]]]

Flatting the initial list produces List<Map<String, Object>> . We can use spread operator * to execute keySet() method on each map stored in the the list:

list.flatten()*.keySet()

This part of the code produces a list of List<List<String>> type like:

[[qunit], [utest]]

Finally, we can convert it to List<String> by calling flatten() in the end, like:

list.flatten()*.keySet().flatten()

After applying the last operation we get a list like:

[qunit, utest]

And here is complete example:

import groovy.json.JsonSlurper

final String json = '[[{"qunit":{"total":0,"passed":0,"failed":0,"skipped":0}}], [{"utest": {"total":0,"passed":0,"failed":0,"skipped":0}}]]'

def list = new JsonSlurper().parseText(json)

def keys = list.flatten()*.keySet().flatten()

assert keys == ['qunit', 'utest']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM