[英]How to get keyset from a string in groovy?
I have a following String in Groovy: 我在Groovy中有以下String:
[[{"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' 我只需要获取键“ qunit”和“ utest”
How is it possible? 这怎么可能?
You can parse that JSON string and then read the list: 您可以解析该JSON字符串,然后阅读列表:
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]
结果是[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: 您的字符串代表一个JSON文档,因此您需要首先使用JsonSlurper
进行解析:
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: 如果您打印list
变量,您将看到类似以下内容:
[[[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>>
. 展平初始列表将产生List<Map<String, Object>>
。 We can use spread operator *
to execute keySet()
method on each map stored in the the list: 我们可以使用扩展运算符*
在列表中存储的每个地图上执行keySet()
方法:
list.flatten()*.keySet()
This part of the code produces a list of List<List<String>>
type like: 这部分代码生成List<List<String>>
类型的列表,例如:
[[qunit], [utest]]
Finally, we can convert it to List<String>
by calling flatten()
in the end, like: 最后,我们可以通过最后调用flatten()
将其转换为List<String>
,例如:
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.