avidCoder
avidCoder

Reputation: 490

How to get all the JSON values for the same keys iterated number of times using groovy?

def json = '{"book": [{"id": "01","language": "Java","edition": "third","author": "Herbert Schildt"},{"id": "07","language": "C++","edition": "second","author": "E.Balagurusamy"}]}'

Using Groovy code, how to get the "id" values printed for "book" array?

Output:

[01, 07]

Upvotes: 0

Views: 498

Answers (1)

Nitin Dhomse
Nitin Dhomse

Reputation: 2622

This is the working example using your input JSON.

import groovy.json.*
def json = '''{"book": [
                         {"id": "01","language": "Java","edition": "third","author": "Herbert Schildt"},
                         {"id": "07","language": "C++","edition": "second","author": "E.Balagurusamy"}
                       ]
              }'''
def jsonObj = new JsonSlurper().parseText(json)
println jsonObj.book.id // This will return the list of all values of matching key.

Demo here on groovy console : https://groovyconsole.appspot.com/script/5178866532352000

Upvotes: 2

Related Questions