Reputation: 7951
Is there a similar notation in Groovy, just like in JavaScript:
{
"name": "Jason Closure"
"characteristics": {
"height": ...,
"weight": ...,
...
}
}
where you can refer to an object key like this:
def content = new JsonSlurper().parseText(json)
def char_key = // char_key can be 'height', 'weight',...
content.characteristics[char_key]
?
Upvotes: 1
Views: 3656
Reputation: 665
My requirement is when the key is also dynamic, how to fetch the value from the json string, the below is the code snippet for the same, locator is the dynamic key in the jsonText. if jsonText is { "name" : "vijay", "address" : { "country" : "IN", "state" : "Telangana", "city" : "hyderabad" } }, then locator can be "name" or "address.state" or "address.city". Please let me know if it needs more clarifications.
def getJsonProperty(String jsonText,String locator){
def slurper = new JsonSlurper()
def result = slurper.parseText(jsonText)
println("responseObject:"+result)
Binding binding = new Binding();
binding.setVariable("result", result);
GroovyShell shell = new GroovyShell(binding)
return shell.evaluate("result."+locator)
}
Upvotes: 0
Reputation: 42184
Yes, you can access JSON nodes using array-like notation, e.g.
import groovy.json.JsonSlurper
def json = '''{
"name": "Jason Closure",
"characteristics": {
"height": 10,
"weight": 20,
}
}'''
def root = new JsonSlurper().parseText(json)
def key = 'height'
assert root.characteristics[key] == 10
You can also get node value using interpolated GString, e.g.
assert root.characteristics."$key" == 10
Upvotes: 4