Groovy web console

subscribe to the feed Subscribe
to this
parse json (via #groovywebconsole)
tweet this snippet Tweet

parse json

Published 4 months ago by nmrao with tags parse json
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def slurper = new groovy.json.JsonSlurper()

//sample json response
def obj = '''{ "bookStore" : [ { "category" : "novel",
    "author" : "Mr. J Thomas",
    "title" : "A Nice Novel",
    "price" : "$25.00"
  { "category" : "biography",
    "author" : "Mrs.Jones",
    "title" : "A Biography of Mr. Jones",
    "price": "$35.00"

def bookData= slurper.parseText(obj)

def verifyBookPrice(bookData, title, expected_value) {
       Map book = bookData.bookStore.find{it.title}
       assert book instanceof Map:"Unable to find the title $title"
       String actual_value = book.price as String
       assert actual_value == expected_value:"The value of field $title is  $actual_value, expecting $expected_value"

//sample book prices to be validated
def books= [ "A Nice Novel" : "\$25.00", "A Biography of Mr. Jones" :    "\$35.00"]
books.each{key, value ->
     verifyBookPrice(bookData, key, value)