Extract only keys from a JSON object using groovy

This is my JSON object

{
"master": {
   "node": "xyz", 
   "files": [{"type": "modified", "file": "test.txt"}]
   }, 
"testbranch2": {
   "node": "abc", 
   "files": [{"type": "modified", "file": "test.txt"}] 
   }, 
"testbranch": {
   "node": "xxx", 
   "files": [{"type": "modified", "file": "test.txt"}], 
   }
}

I need only the key names of the objects, such as "master", "testbranch2", "testbranch". How to get only key object names using groovy?

+4
source share
1 answer

You can use JsonSlurper

import groovy.json.JsonSlurper

def json =  '{ "master": ...'
def test = new JsonSlurper().parseText(json)
//if json comes from file you can do: new JsonSlurper().parse(new File('YOUR_JSON_FILE'))
println test.keySet() 
+5
source

All Articles