Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy & json: How to get the length of an array from json?

I am using curl to get some data, then parsing it with JsonSlurper. The data structure is

"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"
   } 
]

So if I'm not mistaken, the entire thing is considered an object. But there is an array in the object (results) which contains objects in that array.

I need to get the length of the results array. When I try to do json.result.length, I receive a null.

How can I get the length of the results array?

def list = ['curl', '-u', 'user:pass',     "http://localhost:8081/..."].execute()
def json = new JsonSlurper().parseText(list.text)
println json.result.size()
like image 654
crystallinity Avatar asked Dec 15 '22 10:12

crystallinity


1 Answers

What I see is, you are using incorrect property to get the size. Need to use results instead of result. Thats is the reason you are seeing that error as result is null(because there is no such property)

Here is working script and gets output as 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"
like image 159
Rao Avatar answered Dec 16 '22 22:12

Rao