Groovy& json:如何从json获取数组的长度?

时间:2015-11-30 22:04:33

标签: arrays json groovy

我使用curl获取一些数据,然后用JsonSlurper解析它。 数据结构是

"results" : [ 
   {
      "uri" : "http://localhost:8081/artifactory/api/storage/...",
      "created" : "2015-11-27"
   },
   {
      "uri" : "http://localhost:8081/artifactory/api/storage/...",
      "created" : "2015-11-27"
   }, 
   {
      "uri" : "http://localhost:8081/artifactory/api/storage/...",
      "created" : "2015-11-30"
   } 
]

所以,如果我没有弄错的话,整个事物都被认为是一个对象。但是在对象(结果)中有一个数组,其中包含该数组中的对象。

我需要得到结果数组的长度。当我尝试做json.result.length时,我收到一个null。

如何获得results数组的长度?

def list = ['curl', '-u', 'user:pass',     "http://localhost:8081/..."].execute()
def json = new JsonSlurper().parseText(list.text)
println json.result.size()

3 个答案:

答案 0 :(得分:6)

我看到的是,您使用不正确的属性来获取大小。需要使用results代替result。这就是你看到result的错误为空的原因(因为没有这样的属性)

这是工作脚本,输出为3:

import net.sf.json.groovy.JsonSlurper
def jsonText='''{
"results" : [
   {
      "uri" : "http://localhost:8081/artifactory/api/storage/...",
      "created" : "2015-11-27"
   },
   {
      "uri" : "http://localhost:8081/artifactory/api/storage/...",
      "created" : "2015-11-27"
   },
   {
      "uri" : "http://localhost:8081/artifactory/api/storage/...",
      "created" : "2015-11-30"
   }
]
}'''
def json = new JsonSlurper().parseText(jsonText) 
println json.results.size()
assert 3 == json.results.size(), "Array size is not matching"

答案 1 :(得分:1)

它将是:

def response = ... // your response as text, stream..
def parsed = new JsonSluper().parse(response) // parseText if string
println parsed.results.size()

BTW:size()用于Collectionlength用于String,注意方法与字段。在groovy中,您也可以size()使用String

答案 2 :(得分:0)

{
"projects":
  [
  {
    "platform": "java",
    "name":"abc"

  },
  {
    "platform": ".net",
    "name":"abcd"

}]
}

此json文件list.json如何获取json大小或应用程序计数。 下面的代码在我使用jenkinsfile时在Groovy中为我工作。

import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.io.FileType
def applicationCount()
{
  jsonFile1 = 'list.json'
  def json1 = readJSON file: jsonFile1
  totalApplication = json1.projects.size()
  println "count" + totalApplication
  println "applicationname" + json1['projects'][0]['name']
}