Forum Discussion

luluberlu's avatar
luluberlu
Occasional Contributor
6 years ago
Solved

record json response into an array

hello;   i have this kind of API json response :    {"response": {"responseRecherche": { "1": { "Acheteur": { "Id": "azertyui", "Date de création": "2018-03-29 12:19:27", "Date de modificati...
  • JHunt's avatar
    6 years ago

    Or to step back one step further, consider just using the data from the Slurper result directly.

     

    In your case, your JSON is a bit unusual because it labels the objects as "1" and "2" etc

     

            "responseRecherche": {
                "1": { ... },
    "2": { ... },

    Instead of just giving a list as I would normally have expected:

            "responseRecherche": [
                { ... },
    { ... },

    So, yes, in this case it might make sense to partially transform it, into a proper list (not unlike what Rao has suggested):

     

    dumeAcheteurs = new groovy.json.JsonSlurper()
     .parseText(jsonString)
     .response
     .responseRecherche
     .collect { keyName, keyValue -> keyValue } // creates a list from the values behind "1" and "2", ignoring those names for them
     .collect { it.dumeAcheteur }

    Here you're still keeping the whole objects rather than only pulling out a specific subset. And you can just access what you need directly:

     

    assert dumeAcheteurs[0].Id == "azertyui"
    assert dumeAcheteurs[1]."Date de création" == "2018-03-21 10:41:05"
    // etc

     

  • luluberlu's avatar
    luluberlu
    6 years ago

    Hello

     

    thank you for your answers :smileyhappy:

    yesterday we didnt work in france. so i look this morning. 

    I tried quick code with $i but it doesnt' work :(

    After, i try last code with collect function, and it runs very good. 

    i can check all dates before or after a given date, i am very happy to that. thank you so much.

     

    jhunt, yes, this json is a little weak format json, but it is maken by a junior, so ok. in fact, your are a genius :smileywink: