简体   繁体   中英

Extracting specific data from JSON array in groovy

I am trying to extract specific data from a JSON array using groovy. 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. So far the only way that I have come up with this is to use a for loop. Is there a more efficient way to extract the data without iterating through this?

Take a look at 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. Here the iteration is done by 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 elementsByStateAndDay = elements.groupBy { [it."State", it."DayOfWeek"] }
return elementsByStateAndDay.get(["AK", "Tue"]).head()."StartTime"

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