Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch only keys from JSON Object using groovy

Tags:

json

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?

like image 958
shwetha Avatar asked Mar 18 '16 10:03

shwetha


People also ask

Can JSON have only keys?

JSON doesn't have to have only key:value pairs; the specification allows to any value to be passed without a key. However, almost all of the JSON objects that you see will contain key:value pairs.

What does JsonSlurper do?

JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .


1 Answers

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() 
like image 117
user3718614 Avatar answered Nov 15 '22 10:11

user3718614