3 Replies Latest reply on Jul 5, 2006 1:17 PM by foozebox

    Declaring an object with a string

    _bigmac
      Is there a way to declare a data object (at runtime) from a string descriptor? For example, lets say I load a text file that contains the following string: "{name:"bob", age:42, location:"earth"}". Is there a way to then have Flash parse the string and interpret it as an Object object in memory? Thanks!
        • 1. Re: Declaring an object with a string
          foozebox
          Hey.. I have to do this all the time and the best way I've found is to use the JSON (JavaScript Object Notation) class found at:

          http://www.json.org/json.as

          the syntax is:

          import JSON

          var string = "{'var1':'3','var2':'horse'";
          var myObj:Object = JSON.parse(string);

          Just make sure that your variable names are always in quotes and you should be good to go.

          Good luck...-dan
          • 2. Re: Declaring an object with a string
            _bigmac Level 1
            This may be just what I need, thanks for the tip!
            I've set up a quick test though, and I'm having some problems. My code is as follows:

            import JSON;
            var str:String = "{'var1':'hello world'}";
            var obj:Object = JSON.parse(str);
            trace(obj.var1);

            All that I'm getting is an "[object Object]" trace in my output window (upon JSON.parse() calling). Scripts following the parse command do not run (ie: the trace action). And, if I try to access the obj object later (I was checking it upon a button press), then Flash is reporting that obj is undefined. Do you have any insight on this?

            Thanks for your help!!
            • 3. Re: Declaring an object with a string
              foozebox Level 1
              Hey.. yeah the JSON class is a little picky with quotes and double-quotes. It is expecting all name/value pairs to be enclosed in double-quotes.

              Try changing your string to:

              var str:String = '{"var1":"hello world"}';

              and you should be all set. The same goes for any external files, i.e. json_01.txt.
              Hope this helps.