Search code examples
jsongroovyjsonslurper

Getting the only key of a Map from JsonSlurper


I have JSON that needs to be processed using Groovy. I am pretty sure that the JSON has only one key, with this format:

{ rootKey: [...] }

Where rootKey stands for different values (e.g. "customers", "stores", etc.).

Let's say I used JsonSlurper:

def map = jsonSlurper.parseText(myjson)

How do I obtain that rootKey string?


Solution

  • You should be able to use keySet method to get the keys which is a list. Since, you mentioned only key, you can use the first element as shown below:

    def jsonString = """{
      "rootKey": []
    }"""
    def json = new groovy.json.JsonSlurper().parseText(jsonString)
    println json.keySet()[0]