Object from String

Actionscript:
  1. var str:String='{x: 10, y:10, width:100, heigth:100, name:"myClip", type:"clip"}';
  2.  
  3. var obj:Object=toObject(str);
  4.  
  5. trace(obj.x + obj.width, obj.name, obj.type);
  6.  
  7. function toObject(str:String):Object {
  8.     str=str.replace(/\{|\}/g,"");
  9.     // to an array of name value pairs [0] = name, [1] = value etc...
  10.     var pairs:Array=str.split(/\:|\,\s+/);
  11.     var obj:Object = new Object();
  12.     for (var i:int = 0; i<pairs.length; i+=2) {
  13.         obj[pairs[i]]=numOrString(pairs[i+1]);
  14.     }
  15.     return obj;
  16. }
  17. function numOrString(val:*):* {
  18.     if (isNaN(Number(val))) {
  19.         if (val.charAt(0) == '"' && val.charAt(val.length - 1) == '"'){
  20.             val = val.substr(1, val.length - 2);
  21.         }
  22.     } else {
  23.         val=Number(val);
  24.     }
  25.     return val;
  26. }

A very limited way to parse an object from a string... Tomorrow I'll post a better version of this that's a good deal more complex and doesn't really use regular expressions... This works nicely if you don't have arrays as Object properties...

This entry was posted in dynamic, string manipulation, strings and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted April 23, 2009 at 8:47 pm | Permalink

    thx , i love this one , waiting for complex version, this already smaller than JSON, just missing Boolean type ;)

  2. Posted April 23, 2009 at 10:30 pm | Permalink

    thanks katopz… yeah this is pretty limited… booleans would be easy enough to add… just a conditional or two…

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*