0

I want to access a JSON HasMap via String like data['dimension1']['dimension2'] but i want to do that dynamically like data[myAccessor].

Code

import groovy.json.JsonSlurperClassic

dataContent = '''
{
  "Test": {
    "Info": "Hello"
  }
}
'''

def jsonSlurper = new JsonSlurperClassic()
data = jsonSlurper.parseText(dataContent)

println data['Test']['Info']  // Prints 'Hello'

accessor = "'Test']['Info'"
println data[accessor]  // Prints 'null'

'''

2 Answers 2

1

Yeah, you can't just execute complex text as code like that 😕 (or 😄, I can't decide)

The best you can do is to have accessor be something splittable like

accessor = 'Test->Info'

And then you can split this and "walk" down the input structure to get the result you're after like so:

import groovy.json.JsonSlurperClassic

dataContent = '''
{
  "Test": {
    "Info": "Hello"
  }
}
'''

def jsonSlurper = new JsonSlurperClassic()
data = jsonSlurper.parseText(dataContent)

accessor = "Test->Info"

println accessor.split('->').inject(data) { currentData, accessorPart ->
    currentData?.getAt(accessorPart)
}

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you a lot Tim !
Can I also use this Technique to change the Hello Value to some other Value ?
@DirkSchiller Yes. You can reduce along the path except the last element (e.g. using .dropRight(1)) and then put your value with the last element on the resulting map (if there is one)
1

You can leverage Groovy's Eval and represent the accessor with property notation to have something closer to your intent:

import groovy.json.JsonSlurperClassic

dataContent = '''
{
  "Test": {
    "Info": "Hello"
  }
}
'''

def jsonSlurper = new JsonSlurperClassic()
data = jsonSlurper.parseText(dataContent)

println data.'Test'.'Info' // prints 'Hello'
accessor = "'Test'.'Info'"

Eval.x(data, "println x.${accessor}") // prints 'Hello'

2 Comments

Thank you Jalopaba!
One note on eval is to be wary of user input. Someone sending in "X; System.exit(1)" could halt the jvm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.