cancel
Showing results for 
Search instead for 
Did you mean: 

Using Javascript to render JSON: an important gotchas

martin_cowie
Champ in-the-making
Champ in-the-making
Here's the brief: in development of my web scripts, using FreeMarker to output JSON is proving something of an impediment.

Bearing in mind that JavaScript comes with it's own 'Obect.toSource()' method - I thought to use the existing code formatter already baked into Rhino.

However, when running .toSource() on an object that contains embeded Java objects, such as those plucked from the Alfresco API - even simple ones like java.lang.String(), the method would fail with the exception
Method "toSource" called on incompatible object.

The solution, in my case, is to convert strings from Java to Javascript, by appending an empty string. Once done, I can serialise my result in javascript with "result.json = someObject.toSource()"; and my FTL is a simple "${json}".

If anyone knows how to call "someObject.toSource()" from the freemarker side, that would be nicer still.

M.
2 REPLIES 2

davidc
Star Contributor
Star Contributor
What's the impediement?

martin_cowie
Champ in-the-making
Champ in-the-making
The impediment in this case is the time spent on the FreeMarker learning curve, teaching myself how to recurse through an object-model (built in JavaScript) to render a piece of JSON, when I was really re-inventing the wheel - as the Rhino engine already has this ability.

The model-view separation has merit, for all sort of reasons, but rendering JSON and indeed XML in FreeMarker is a painful business, and on best done with tools already bake into JavaScript.

It is possible in the FreeMarker to call a JavaScript function to do this rendering?

Cheers,

M.