Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from a JSON (string) in Groovy

Tags:

json

groovy

I have been struggling to figure out how to get a parameter out of a JSON string in Groovy.

I have a string similar to:

'{"id":"12345678","name":"Sharon","email":"sharon\u0040example.com"}'

and am trying to extract the email address.

I can of course use regex, or other substring methods, but I'm sure there is a cleaner way.

like image 464
Zach Lysobey Avatar asked Aug 20 '13 21:08

Zach Lysobey


People also ask

What is groovy JSON JsonSlurper?

JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.


1 Answers

Use JsonSlurper.

import groovy.json.JsonSlurper

def str = '{"id":"12345678","name":"Sharon","email":"sharon\u0040example.com"}'
def slurper = new JsonSlurper().parseText(str)

assert slurper.email == '[email protected]'
assert slurper.name  == 'Sharon'
like image 70
dmahapatro Avatar answered Oct 20 '22 10:10

dmahapatro