Search code examples
groovycollectionsjsonslurper

Obtaining a random value using Groovy JsonSlurper


I'm new to Groovy and trying to understand the best way of approaching this. Apologies for an elementary question.

Given a Json file vehicles.json of:

{
  "prod": [
    {
      "id": "CAR LARGE",
      "vehicle": "102920",
      "name": "BMW 325"
    },
    {
      "id": "CAR MEDIUM",
      "vehicle": "192039",
      "name": "VOLVO V40"
    },
    {
      "id": "CAR SMALL",
      "vehicle": "29303",
      "name": "SMART 500"
    }
  ], 
  "preprod": [
   {///entries for this environment...

I want to pick a random Car for a given environment, then extract it's vehicle and name properties into List of 2 for future use (in reality the list is very long)

This method will get a random vehicle number:

    def getVehicle() {
        def jsonSlurper = new JsonSlurper()
        def envVehiclesList = jsonSlurper.parseText(new File('src/main/resources/data/vehicles.json').text)

        List<String> vehicleList = new ArrayList<>();
        switch (System.getProperty("env")) {
            case "prod":
                vehicleList = (envVehiclesList.prod*.vehicle)
                break;
            case "preprod":
                vehicleList = (envVehiclesList.preprod*.vehicle)
                break;
            case "dev":
                vehicleList = (envVehiclesList.dev*.vehicle)
                break;
            default:
                vehicleList = "18292" as List<String>
        }

        def rand = new Random()
        def randomVehicle = vehicleList.get(rand.nextInt(vehicleList.size()))
        log.info("Random Base Vehicle: {}", randomVehicle)
        return randomVehicle
    }

This gives me a random vehicle e.g. 192039. I need to be able to extract the name associated with the randomly chosen vehicle and store it in a List or Object so I can extract both for future use e.g. randomVehicle stores both 29303, SMART 500 and I can get by index from a list or use a getter if stored in an Object.

Any suggestions would help my learning. Thank you.


Solution

  • def input = """
    {
      "prod": [
        {
          "id": "CAR LARGE",
          "vehicle": "102920",
          "name": "BMW 325"
        },
        {
          "id": "CAR MEDIUM",
          "vehicle": "192039",
          "name": "VOLVO V40"
        },
        {
          "id": "CAR SMALL",
          "vehicle": "29303",
          "name": "SMART 500"
        }
      ]
    }
    """
    
    def jsonSlurper = new groovy.json.JsonSlurper()
    def envVehiclesList = jsonSlurper.parseText(input)
    def env = "prod"
    def vehicleList = []
        
    switch (env) {
        case "prod":
        vehicleList = (envVehiclesList.prod)
        break;
        case "preprod":
        vehicleList = (envVehiclesList.preprod)
        break;
        case "dev":
        vehicleList = (envVehiclesList.dev)
        break;
        default:
            throw new IllegalArgumentException("Unknown Environment: $env")
    }
    
    def rand = new Random()
    def randomVehicle = vehicleList.get(rand.nextInt(vehicleList.size()))
    println("Random Base Vehicle: $randomVehicle")
    

    Just don't select .vehicle, then you have all the data. Try it in the Groovy Web Console