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

27,371

Solution 1

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"

Solution 2

It will be:

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

BTW: size() is for Collection, length for String, note method vs field. In groovy you can use size() for String as well.

Share:
27,371
crystallinity
Author by

crystallinity

Updated on January 19, 2020

Comments

  • crystallinity
    crystallinity over 4 years

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