how to parse json using groovy
Asked Answered
C

5

58

I want to parse JSON data which is coming in like:

{
   "212315952136472": {
      "id": "212315952136472",
      "name": "Ready",
      "picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/195762_212315952136472_4343686_s.jpg",
      "link": "http://www.hityashit.com/movie/ready",
      "likes": 5,
      "category": "Movie",
      "description": "Check out the reviews of Ready on  http://www.hityashit.com/movie/ready"
   }
}

The code I am using is:

JSONElement userJson = JSON.parse(jsonResponse)
userJson.data.each {
    Urls = it.link
}

But I am not able to get anything assigned to Urls. Any suggestions?

Chronologist answered 14/7, 2011 at 3:15 Comment(0)
S
63

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link
Smuggle answered 14/7, 2011 at 3:31 Comment(2)
Burt, what am I supposed to import to make the first example code block work? I figured out i need import org.codehaus.groovy.grails.web.json.JSONObject but then it fails stating "No such property: JSON"Storage
Got it - from here. It's import grails.converters.JSONStorage
E
84

Have you tried using JsonSlurper?

Example usage:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
Exonerate answered 14/7, 2011 at 8:24 Comment(4)
This is for Groovy 1.8 and later only.Dempsey
Awesome! You may need to import groovy.json.JsonSlurperKaduna
This does not answer the question, as the question has a dynamic id (like 212315952136472) as part of the path. Could you please update your example to use the question's data? Thanks!Foreshore
@NicolasRaoul def result = slurper.parseText(jsonResponse); assert result['212315952136472'].link == 'http://www.example.com/movie/ready'Frontality
S
63

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link
Smuggle answered 14/7, 2011 at 3:31 Comment(2)
Burt, what am I supposed to import to make the first example code block work? I figured out i need import org.codehaus.groovy.grails.web.json.JSONObject but then it fails stating "No such property: JSON"Storage
Got it - from here. It's import grails.converters.JSONStorage
G
6

You can convert JSON to the desired type in Groovy using as operator:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}
Grugru answered 11/3, 2017 at 15:7 Comment(0)
N
0
def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();

def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)

def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
Nara answered 18/8, 2020 at 9:2 Comment(0)
J
0

The thing with this unique number is a bit tricky.

If you know this value, easy

stage('Test Groovy JSON parsing') {
    steps {
        script {
            def userJson = readJSON file: 'myJsonFile.json'

            def keyList = userJson['212315952136472'].keySet()
            echo "${keyList}"   // ['id', 'name', 'picture', 'link', 'likes', 'category', 'description']
            
            echo "${userJson['212315952136472'].name}"  // Ready
            echo "${userJson['212315952136472'].link}"  // http://www.hityashit.com/movie/ready
        }
    }
}

If you don't know this number, you could walk through the JSON

userJson.each { key, value ->
    echo "Walked through key $key and value $value"
}

check also the documentation at Jenkins Read JSON from File

Jerrelljerri answered 2/3, 2021 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.