Groovy - JSON Object Operations
Groovy provides JsonSlurper to parse JSON string intuitively. When a json object is encountered, it is converted into a groovy Map instance automatically. In this chapter, we'll demonstrating various operations on JSON objects parsed using JsonSlurper.
Accessing JSON Objects Elements
We can access JSON object elements using dot notation as well using square brackets [] as shown in example below −
Example.groovy
import groovy.json.JsonSlurper
def jsonObjectText = '''
{
"name": "Julie",
"age": 32,
"id": 1,
"isManager": false,
"courses" : ["java", "python"]
},
'''
def slurper = new JsonSlurper()
def employee = slurper.parseText(jsonObjectText)
// Access object elements using dot notation
// prints Julie
println employee.name
// prints 32
println employee.age
// prints 1
println employee.id
// prints false
println employee.isManager
// prints [java,python]
println employee.courses
// access object properties using square brackets
def key = "age"
println employee[key] // prints 32
// prints false
println employee["isManager"]
Output
When we run the above program, we will get the following result.
Julie 32 1 false [java, python] 32 false
Modifying JSON Object elements
We can modify JSON Objects as being regular Groovy objects as shown in example below −
Example.groovy
import groovy.json.JsonSlurper
def jsonObjectText = '''
{
"name": "Julie",
"age": 32,
"id": 1,
"isManager": false,
"courses" : ["java", "python"]
},
'''
def slurper = new JsonSlurper()
def employee = slurper.parseText(jsonObjectText)
employee.age = 36
employee.id = 2
employee.city = "Dalas" // Adding new key value pair
employee.courses << "angular" // add a new value to list
println employee
Output
When we run the above program, we will get the following result.
[age:36, city:Dalas, courses:[java, python, angular], id:2, isManager:false, name:Julie]
Iterating over each element of JSON Object
JSON Object being regular map, can be iterated easily as shown in example below −
Example.groovy
import groovy.json.JsonSlurper
def jsonObjectText = '''
{
"name": "Julie",
"age": 32,
"id": 1,
"isManager": false,
"courses" : ["java", "python"]
},
'''
def slurper = new JsonSlurper()
def employee = slurper.parseText(jsonObjectText)
// using each iterator
employee.each { key, value ->
println "Key: ${key}, Value: ${value}"
}
// using eachWithIndex Iterator
employee.eachWithIndex { entry, index ->
println "Entry #${index + 1}: Key - ${entry.key}, Value - ${entry.value}"
}
Output
When we run the above program, we will get the following result.
Key: age, Value: 32 Key: courses, Value: [java, python] Key: id, Value: 1 Key: isManager, Value: false Key: name, Value: Julie Entry #1: Key - age, Value - 32 Entry #2: Key - courses, Value - [java, python] Entry #3: Key - id, Value - 1 Entry #4: Key - isManager, Value - false Entry #5: Key - name, Value - Julie
Advertisements