How to create an object form a string in actionscript 3.0 (as3)

Ben picture Ben · Oct 2, 2009 · Viewed 13k times · Source

How can I create a dynamic object from a string?

Here is my current code with incorrect results:

var s1:String = '{x:200, y:400}';
var o1:Object = Object(s1);

trace(o1); // result = {x:200, y:400}
trace(o1.x) // result = ReferenceError: Error #1069: Property x not found on String and there is no default value.
trace(o1.y) // result = ReferenceError: Error #1069: Property x not found on String and there is no default value.

I would like the previous code to output the following:

trace(o1); // result = [object Object]
trace(o1.x); // result = 200
trace(o1.y); // result = 400

Thanks in advance!

Answer

spender picture spender · Oct 2, 2009

as3corelib contains a JSON parser that would do this for you. Make sure you study the issues list as there have been no new releases of this library and there are plenty of bugs in it, that are mostly addressed in the issues list.