使用groovy仅从JSON对象获取键

shw*_*tha 4 groovy json

这是我的JSON对象

{
"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"}], 
   }
}
Run Code Online (Sandbox Code Playgroud)

我只需要对象键名称,如"master","testbranch2","testbranch.我如何使用groovy只获取对象键名?

use*_*614 6

您可以使用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() 
Run Code Online (Sandbox Code Playgroud)