shwetha
shwetha

Reputation: 376

Fetch only keys from 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 object key names, like "master", "testbranch2","testbranch. How do I fetch only the object key names using groovy?

Upvotes: 6

Views: 12399

Answers (1)

user3718614
user3718614

Reputation: 530

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() 

Upvotes: 10

Related Questions