cancel
Showing results for 
Search instead for 
Did you mean: 

jsonUtils.toObject() not behaving as expected

dlamoris
Champ in-the-making
Champ in-the-making
Hi all,

I'm creating a webscript that processes content posted as json. In the script, I got the root 'json' object ok, but when I try to convert it to a native js object using jsonUtils.toObject(json), I can't figure out what's going on…

example posted json:
{"a": [{"b": "c"}, {"d": "e"}]}

when i do:
<javascript>
var test = jsonUtils.toObject(json);
</javascript>

Using the alfresco javascript debugger and the Expression window, here's what I see:

json                      {"a": [{"b": "c"}, {"d": "e"}]}
test                      TypeError: Cannot find default value for object.
test.a                    [{"b": "c"}, {"d": "e"}]
test.a.length         
test.a.size               function size() {/* int size() */}
test.a.get                function get() {/* java.lang.Object get(int) */}
test.a[0]                 Java class "org.json.simple.JSONArray" has no public instance field or method named "0".
test.a.get(0)             null
test.a.getJSONObject(0)   TypeError: Cannot find function getJSONObject. 

This is confusing enough. From the documentation it seems that jsonUtils.toObject should return a native javascript object, except array values were not converted, and I can't even use functions from JSONArray java object? I'm struggling to iterate over the array that's the value of "a".

Any help is appreciated!
1 REPLY 1

eric_soto
Champ in-the-making
Champ in-the-making
dlamoris,

If you want to iterate over the a array in order to retrieve its values, this is one way to do it:


var json = {"a": [{"b": "c"}, {"d": "e"}]};

for each (aArray in json.a) {
  if(typeof aArray.b != "undefined") {
    b_value = aArray.b;
  }
  if(typeof aArray.d != "undefined") {
    d_value = aArray.d;
  }
}


The b_value variable would contain "c" and d_value would contain "e".

Hope this helps! Cheers.