cancel
Showing results for 
Search instead for 
Did you mean: 

How do I parse JSON in a Share Component?

bjornd
Champ in-the-making
Champ in-the-making
How do I access the Rhino JSON parser from webscript .js code that is part of a Share Component? Or access any other secure non-evaluating JSON parser for that matter.
3 REPLIES 3

sonata82
Champ in-the-making
Champ in-the-making

bjornd
Champ in-the-making
Champ in-the-making
The only thing I found was using the JsonUtils from SpringSurf: http://www.springsurf.org/sites/1.0.0.M3/spring-webscripts/spring-webscripts-documentation/reference...
Thanks for the suggestion, but jsonUtils.toObject doesn't work in Alfresco, it produces instead "Expected collection or sequence. foo evaluated instead to freemarker.ext.beans.StringModel".

This is the logged error when the "Object" is received by freemarker.

If I use "eval()" instead, freemarker receives the intended object and everything works. But eval() is of course totally forbidden for the purposes of parsing JSON data in any serious project, so I was just wondering how everybody else deals with this?

bjornd
Champ in-the-making
Champ in-the-making
The freemarker error message turned out to be a red herring. The object that was expected to be a JavaScript array was actually a Java object of the class org.json.JSONArray returned by jsonUtils.toObject. As documented, by the way, but still somewhat confusing. Java JSONArrays are not compatible with JavaScript arrays since element access is handled in a completely different way.

I solved my problem by including Douglas Crockford's public-domain parser in my code. I found it via the link at the bottom of the page http://www.json.org/js. This is how I use it:
var connector = remote.connect("alfresco");
var response = connector.get("/my/service/url");
var data = json_parse(response + "");
The response+"" thing on the last line converts the object returned by connector.get into a real JavaScript string. The original object is not a real JavaScript string, it lacks some of the standard string methods, which are used by the JSON parser.