Created
January 24, 2012 20:23
-
-
Save narenranjit/1672345 to your computer and use it in GitHub Desktop.
Convert objects in Velocity templates to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#macro(VelListToJSON $list ) | |
#set($myList = $list )## dereference | |
{ | |
#foreach($key in $myList.keySet()) | |
"$key": | |
#set($x = $myList.get($key)) | |
#VelToJSON($x) | |
#if($foreachCount != $myList.keySet().size()) , #end | |
#end | |
} | |
#end | |
#macro(VelArrayToJSON $arr) | |
#set($myArr = $arr) | |
[ | |
#foreach($x in $myArr) | |
#VelToJSON($x) | |
#if($foreachCount != $myArr.size()) , #end | |
#end | |
] | |
#end | |
##TODO: Make it not treat numbers as strings | |
#macro(VelToJSON $item) | |
#if($item.keySet()) | |
#VelListToJSON($item) | |
#elseif($item.size()) | |
#VelArrayToJSON($item) | |
#elseif($item == true || $item ==false) | |
$item | |
#else | |
"$item" | |
#end | |
#end |
Please note that JSON (like JavaScript) has encoding and escaping rules that will not be followed by this code. So for example, if your strings are allowed to contain characters like "
and \
, then you have an injection vulnerability. You could make use of the EscapeTool
builtin, but you would need to put that on the template context, e.g., $esc
.
Sorry for the question, I'm new to VTL, but it would be nice to have a usage example of the code above..
@sacredwx I haven't done velocity for a while but you should be able to do something like
#set($data = ["a", "b"])
#VelListToJSON($data)
thank you for suggestion!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@TheClassic gists don't support notifications :(
you won't get this mention but maybe you'll revisit this topic someday :)