简体   繁体   English

从 groovy 中的 JSON 数组中提取特定数据

[英]Extracting specific data from JSON array in groovy

I am trying to extract specific data from a JSON array using groovy.我正在尝试使用 groovy 从 JSON 数组中提取特定数据。 This is an example of the array:这是数组的一个示例:

{
"elements": [
    {
        "State": "AK",
        "DayOfWeek": "Mon",
        "StartTime": "0900",
        "EndTime": "2200"
    },
    {
        "State": "AK",
        "DayOfWeek": "Tue",
        "StartTime": "0900",
        "EndTime": "2200"
    },
    {
        "State": "AK",
        "DayOfWeek": "Wed",
        "StartTime": "0900",
        "EndTime": "2200"
    }]}

In this case, I want to extract the StartTime from AK when the DayOfWeek is Tue.在这种情况下,我想在 DayOfWeek 是 Tue 时从 AK 中提取 StartTime。 So far the only way that I have come up with this is to use a for loop.到目前为止,我想出的唯一方法是使用 for 循环。 Is there a more efficient way to extract the data without iterating through this?有没有更有效的方法来提取数据而无需迭代?

Take a look at JsonSlurper看看 JsonSlurper

Something like this:像这样的东西:

def json = new JsonSurper().parseText(".....")
json.elements.each(element -> {
        // logic to extract what you want
    });

Ultimately there will be some iteration involved regardless of the implementation.无论实现如何,最终都会涉及一些迭代。 Groovy helps us to write it more expressively, though.不过,Groovy 可以帮助我们更有表现力地编写它。 Here the iteration is done by find :这里的迭代是由find完成的:

List elements = new groovy.json.JsonSlurper().parseText('''{
"elements": [
    {
        "State": "AK",
        "DayOfWeek": "Mon",
        "StartTime": "0900",
        "EndTime": "2200"
    },
    {
        "State": "AK",
        "DayOfWeek": "Tue",
        "StartTime": "0900",
        "EndTime": "2200"
    },
    {
        "State": "AK",
        "DayOfWeek": "Wed",
        "StartTime": "0900",
        "EndTime": "2200"
    }]}''')."elements"

return elements.find { it."State" == "AK" && it."DayOfWeek" == "Tue" }."StartTime"

Since you tagged this as 'simplify', presumably when you asked for something more efficient what you really meant was that you want to write less code, so the above suits.由于您将其标记为“简化”,大概当您要求更高效的东西时,您真正的意思是您想要编写更少的代码,所以上面的适合。

If lookup performance was the issue because you want to do many searches, you could use a Map to index the elements (once), and then getting data becomes a matter of doing a lookup rather than a search:如果查找性能是问题,因为您想要进行多次搜索,您可以使用 Map 来索引元素(一次),然后获取数据就变成了查找而不是搜索的问题:

Map elementsByStateAndDay = elements.groupBy { [it."State", it."DayOfWeek"] }
return elementsByStateAndDay.get(["AK", "Tue"]).head()."StartTime"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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