Groovy web console

subscribe to the feed Subscribe
to this
site
parse json and extract value (via #groovywebconsole)
tweet this snippet Tweet
this
script

parse json and extract value

Published 2 months ago by nmrao with tags parse json
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def str = """{     "data": [{             "Name": "ABCD",             "Mobile": "9876543210"         },         {             "Name": "EFGH",             "Mobile": "8765432109"         },         {             "Name": "IJKL",             "Mobile": "7654321098"         },         {             "Name": "MNOP",             "Mobile": "6543210987"         }     ] }"""
def json = new groovy.json.JsonSlurper().parseText(str)
//def entries = json.data.collec{it}.find{key, value -> key == 'Name' && value == 'EFGH'}
//collect{it}.inject([:]){map,entry -> map[entry.key] = entry.value;map}
//def getMobile = { key, value, map -> if (map[key] == value) return map['Mobile']}
//def result = json.data.inject([]) { li, item -> def m = getMobile('Name', 'EFGH', item); if (m) { li << m};li }[0]
//def result = json.data.inject([]) { li, item -> if (item['Name'] == 'EFGH'){ li << item['Mobile']} ;li }[0]
def result = json.data.find { it.Name == 'EFGH' }.Mobile
println result

//println entries