views:

1483

answers:

3

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!

+4  A: 

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.

spender
I was just about to answer the same thing :) to solve the specific problem you'll be using the JSON class in that lib: `JSON.decode(str)` and `JSON.encode(obj)` to go the other way.
JStriedl
About the bugs, there are people fixing it. See: http://code.google.com/p/as3corelib/source/list . You just need to check out from the SVN.
Andy Li
As I said, "no new releases", but yes, this is good to know.
spender
+3  A: 

I don't know if this is the best way, but:

var serializedObject:String = '{x:200,y:400}'
var object:Object = new Object()

var contentWithoutBraces:String = serializedObject.substr(serializedObject.indexOf('{') + 1)
contentWithoutBraces = contentWithoutBraces.substr(0, contentWithoutBraces.lastIndexOf('}'))

var propertiesArray:Array = contentWithoutBraces.split(',')

for (var i:uint = 0; i < propertiesArray.length; i++)
{
    var objectProperty:Array = propertiesArray[i].split(':')

    var propertyName:String = trim(objectProperty[0])
    var propertyValue:String = trim(objectProperty[1])

    object[propertyName] = Object(propertyValue)
}

trace(object)
trace(object.x)
trace(object.y)

This will do what you want.

You can do this in a recursive manner so if the object contains other objects also are converted ;)

PS: I don't add the trim function, but this function recieve a String and returns a new String without spaces at the beginning or at the end of the String.

unkiwii
+1  A: 

For the record, the JSON parser won't parse the string in the example, since JSON requires quotes around member names. So the string:

var s1:String = '{x:200, y:400}';

... would instead have to be:

var s1:String = '{"x":200, "y":400}';

It can be a bit confusing that object notation, like {x:200, y:400}, that is valid in both ActionScript and JavaScript is not valid JSON, but if I remember it right, the quotes around member names are necessary to avoid possible conflicts with reserved words.

http://simonwillison.net/2006/Oct/11/json/

Lars