How To Parse JSON with Groovy

In this tutorial we’re going to see example how to work with JSON in Groovy and how to parse it. We’ll make it as simple as it is, so we don’t need to add any external dependency, just run it like a shell scripts. For this tutorial we’ll use Groovy 4.*, but it should work on Groovy 3+

We’re going to parse JSON from file and string, there’s no differences between them, depend on the use case you’re facing.

File JSON

Let’s create a dummy JSON file (file.json) as example.

{
  "name": "Jack Tux",
  "job_role": [
    "DevOps",
    "SRE",
    "DBA"
  ],
  "dob": "12-12-2012",
  "address": {
    "street": "S Africa Rd",
    "city": "London",
    "country": "England"
  }
}

Parse JSON

In Groovy we’ll use JsonSlurper class to parse JSON. Let’s create a parse.groovy file with following code

import groovy.json.JsonSlurper
 
def jsonSlurper = new JsonSlurper()
def fileJson = new File("/home/jack/file.json")
def InputJSON = jsonSlurper.parseFile(fileJson, 'UTF-8')
 
InputJSON.each{ println it }

/home/jack/file.json is the full PATH for file.json above. Then run the scripts

$ groovy parse.groovy 
name=Jack Tux
job_role=[DevOps, SRE, DBA]
dob=12-12-2012
address={street=S Africa Rd, city=London, country=England}

Parse String

For another example we’re going to parse JSON from string, not from file directly like example above

import groovy.json.JsonSlurper
 
def jsonSlurper = new JsonSlurper()
def InputJSON = jsonSlurper.parseText('{"name":"Jack Tux","job_role":["DevOps","SRE","DBA"],"dob":"12-12-2012","address":{"street":"S Africa Rd,","city":"London","country":"England"}}
 
InputJSON.each{ println it }

it’ll return the same output.
groovy json result

To get each key from the JSON use

println InputJSON.name
println InputJSON.job_role
println InputJSON.dob
println InputJSON.address
println InputJSON.address.country
# output
Jack Tux
[DevOps, SRE, DBA]
12-12-2012
[street:S Africa Rd, city:London, country:England]
England

To print job_role from array

InputJSON.job_role.each{ println it }
# output
DevOps
SRE
DBA

To make it easier to read, some people prefer to use for loop, it should get the same result

for (item in InputJSON.job_role) {
  println item
}
# output
DevOps
SRE
DBA

Leave a Comment