Biren Barodia
Biren Barodia

Reputation: 43

How to convert a string to a map in velocity

I have something like:

set( $userPrefs = ${subscription.getUserPreferences()} )

getUserPreferences() returns a string which is actually a JSON value that is escaped.

doing "text" : $userPrefs returns [object]

I see something called a Map here

How can I convert my data which is like:

$userPrefs = "{\"a\": \"b\",\"c\": \"d\"}"

into a map?

Thanks

Upvotes: 2

Views: 2716

Answers (2)

Pascal
Pascal

Reputation: 59

Thxs I can do it too :-)

Test
#set($raw = '{"foo":"bar", "baz":5}')
#set($assign = "$escapetool.getHash()set($map = $raw)")
#evaluate($assign)
Test (must display bar value) : $map.foo

Upvotes: 1

Claude Brisson
Claude Brisson

Reputation: 4130

The proper way of doing this would be to put a JSON deserializer tool in your context.

This said, if you have access to VelocityTools in your context, then you can indeed do something with the $render tool:

#set($raw = '{"foo":"bar", "baz":5}')
#set($assign = "${esc.hash}set($map = $raw)")
$!render.eval($assign)
#if($map)JSON parsing succeeded: map=$map #else JSON parsong failed #end

But this approach looks rather hackish, plus the Velocity literal map syntax is not strictly in conformance with JSON, especially around escaping. You should rather use a proper JSON deserializer tool.

Upvotes: 1

Related Questions