PDA

View Full Version : Is Eval needed here?



GregT
26 Nov 2009, 6:26 AM
Given this JSON:



{"result":
{"f":
[
{"x":"y"}
],
"g":
{
"j":"k"}
}
}
}


The point is, 'f' contains a set of 'records', whereas 'g' contains a single value.

It is no problem to parse 'f.x' out of here using a JsonReader, but what is the correct way to obtain the value of 'g.j'?

This seems to work:

eval(result).g.j;

... but as I understand it, 'eval' is to be avoided. Is this a case where it is unavoidable, or is there some other way to do this? I tried experimenting with different configurations of JsonReader as well as Ext.util.JSON.decode.

Any advice appreciated.

hendricd
26 Nov 2009, 8:42 AM
GregT:

Ext.decode uses eval (unless Ext.USE_NATIVE_JSON == true) to parse your incoming JSON string into a object.


var o = Ext.decode( response.responseText);

console.log( o.g.j ) ;
Just stick with the standard Ext methods, and you'll be fine.

GregT
26 Nov 2009, 8:52 AM
Thank you Doug, but I tried that before and I get 'missing ] after element list'. This happens during the 'decode' statement.

I am pretty sure my JSON is clean because 'eval', when called directly, parses it just fine (also, it looks fine visually and finally, it is being emitted by GSON which I have not yet seen screw anything up).

So I have no clue what this error means. Any thoughts?

hendricd
26 Nov 2009, 9:30 AM
This isn't right:



"g":
{
"j":"k"}
}

GregT
26 Nov 2009, 9:37 AM
My apologies, that was a typo when I simplified my example to post it here.

The full JSON is a fairly big chunk of text (too big to post here) with everything paired up properly, trust me ;)

Since 'eval' can handle it, shouldn't 'decode' be able to as well? I guess 'decode' does more than just run 'eval'...

VinylFox
26 Nov 2009, 10:00 AM
Its really quite straight forward...


doDecode = function(json){
return eval("(" + json + ')');
}

doDecode is what is called by decode if there is no native JSON support in the browser.

Try running your full JSON through JSONLint (http://www.jsonlint.com).

hendricd
26 Nov 2009, 10:06 AM
@Greg -- your incoming string should have CRLF encoded as \n, and embedded quotes need to be escaped as well ( "O\'brian" ).

Good luck