9 Replies Latest reply on Jul 31, 2007 2:34 PM by Newsgroup_User

    JSON?

    NickTheNameless Level 1
      I would like to use an external data feed that is formatted in JSON. If the information was XML, I would have very few questions. How do I request, retrieve, and display information with JSON?
        • 1. Re: JSON?
          Level 7
          Hi Nick,

          I think the JSON class provides two methods for serializing and
          deserializing. To serialize an object (to send to JavaScript, for
          example), call:

          JSON.encode(objectRef);

          For example, say you have a complex object like this:

          var myObj:Object=new Object();
          myObj.numberVal=12;
          myObj.stringVal='blah';
          myObj.otherObj=new Object();

          To get the serialized JSON string, you would call:

          var JSONString:String=JSON.encode(myObj);

          Notice it's static so you don't need an instance of the JSON class to
          call this method.

          To deserialize data from a JSON string to a native object:

          var myObj:Object=JSON.decode(someJSONString);

          The 'someJSONString' variable is the JSON string you received from
          somewhere. Could be JavaScript, the server...doesn't matter.

          JSON will serialize it to a native Flash object. So, if you create an
          array in JavaScript, for example:

          //This is JavaScript
          var myObj=new Object();
          myObj.myArr=['a','b'];
          var JSONString=JSON.encode(myObj);

          ...in Flash, you would get a native object, inside that object an array
          named 'myArr, and that array would have two elements ('a', and 'b').

          That's as complicated as it gets! JSON literally just transcodes from
          native objects like numbers, strings, etc. to a formatted string (you
          can trace this out to see what the JSON format looks like), and then
          back into the native data type when that string hits its destination.

          JSON is pretty good for this purpose. Flash has its own binary serial
          format which is faster but not exactly universal. I have a library in my
          API called XMLs (XLMserial) which does the same thing...but it has more
          overhead than JSON.

          Hope that helps,
          Patrick

          NickTheNameless wrote:
          > I would like to use an external data feed that is formatted in JSON. If the information was XML, I would have very few questions. How do I request, retrieve, and display information with JSON?

          --
          http://www.baynewmedia.com
          Faster, easier, better...ActionScript development taken to new heights.
          Download the BNMAPI today. You'll wonder how you ever did without it!
          Available for ActionScript 2.0/3.0.
          • 2. Re: JSON?
            Greg Dove Level 4
            If you want to decode it inside flash you just need to get hold of the raw text encoded as JSON and have supported decoder class.
            I'd imagine you just need to LoadVars it and catch it in the onData handler (before flash tries to parse it as normal). Then use an actionscript JSON decoder to parse it. I'm not sure how you'd get on with cross-domain restrictions though. Is it from the same domain.

            I guess other options would be to catch it and parse it with javascript and then pass it on via externalInterface... but why not grab it directly?

            There are some supporting classes at JSON.org

            I've used a slightly modified one from Patrick Minneault - but I was using it for flashvars not live data. I took a look for it just now, but couldn't find it. Let me know if you really need it and I'll track down the link via a bit of searching.

            Neither for me were perfect. Either that or the php json_encode function doesn't encode to the same standard. I managed to fix the one thing that was happening that was strange.

            • 3. Re: JSON?
              NickTheNameless Level 1
              thanks to both of you, after reading GWD's post i realize i need to Patrick B's method of using JavaScript because the feed is not on the same server. i'll wait to mark it as the answer till i get it running.

              thanks again.
              • 4. Re: JSON?
                Greg Dove Level 4
                That would be right. You can use the other approach only if you have control over the crossdomain.xml unless there's some new way to avoid that.

                • 5. Re: JSON?
                  Level 7
                  A server-side script (PHP, for example), that passes data from another
                  domain as though it were coming from your own. Such a script is
                  surprisingly easy to write.

                  JavaScript doesn't allow crossdomain scripting anyways so you'll be
                  limited in your options if you can't do a crossdomain XML file.

                  Patrick

                  GWD wrote:
                  > That would be right. You can use the other approach only if you have control over the crossdomain.xml unless there's some new way to avoid that.
                  >
                  >

                  --
                  http://www.baynewmedia.com
                  Faster, easier, better...ActionScript development taken to new heights.
                  Download the BNMAPI today. You'll wonder how you ever did without it!
                  Available for ActionScript 2.0/3.0.
                  • 6. Re: JSON?
                    Greg Dove Level 4
                    @ patrick Yeah... I thought of that afterwards too... (I guess its not new, though ;-) but I didn't know about there being restrictions for Javascript, haven't really done much with js.
                    • 7. Re: JSON?
                      Level 7
                      JS and Flash have similar domain restrictions. Flash is a bit more
                      flexible if you can upload crossdomain.xml files but it can still be a
                      hastle.

                      Here's a quick PHP script I wrote that acts as, basically, a proxy for
                      Flash:

                      $address=$_POST['address'];
                      $proxyData=file_get_contents($address);
                      $fileSize=strlen($proxyData);
                      header('Content-Type: text/html'); //Change the content type if you
                      want to load something else like an image or something
                      header("Content-Length: " .$fileSize);
                      header("Cache-Control: no-cache, must-revalidate");
                      header ("Date: ".date("r"));
                      header("Expires: Mon, 01 Jan 2007 00:00:00 GMT");
                      header("Host: ".$_SERVER['HTTP_HOST']);
                      header("Server: My Super Special Proxy Thingie v1.0");
                      echo ($proxyData);

                      This uses a post variable, "address" to determine where to grab the data
                      from. In Flash, using LoadVars, you would call the request like this:

                      var result_lv:LoadVars = new LoadVars();
                      var send_lv:LoadVars = new LoadVars();
                      send_lv.address= " http://www.someaddress.com/someData.xml"; //or
                      whatever you want to load
                      send_lv.sendAndLoad("theAboveScript.php", result_lv, "POST");

                      Feel free to use and abuse :)

                      Patrick

                      GWD wrote:
                      > @ patrick Yeah... I thought of that afterwards too... (I guess its not new, though ;-) but I didn't know about there being restrictions for Javascript, haven't really done much with js.

                      --
                      http://www.baynewmedia.com
                      Faster, easier, better...ActionScript development taken to new heights.
                      Download the BNMAPI today. You'll wonder how you ever did without it!
                      Available for ActionScript 2.0/3.0.
                      • 8. Re: JSON?
                        Greg Dove Level 4
                        Well it seems like no matter what you could find a way to work with it directly in flash.
                        I found the link to the one I used its here:

                        http://www.5etdemi.com/blog/archives/2006/05/cinqetdemijson-a-better-json-parser-for-as2-s uited-for-config-files/

                        JSON.as is the file with the class you need for decoding directly in flash.
                        And the issue I had with PHP json_encode content was the \x single hex encoded char value

                        \u worked for utf/double byte but \x wasn't implemented in this decoder/encoder -which isn't surprising because it looks like its not part of the JSON standard. But I was receiving this for something from php... can't remember exactly what or why. After observing it I just patched the class file to include it and all was well.

                        If you strike the same issue then you can fix it by including this additional case clause in the private function str - this is for decoding. I didn't need the encoding part so didn't try to implement this change in the 'stringify' function


                        • 9. Re: JSON?
                          Level 7
                          Good to know, thanks GWD.

                          One other warning I would offer to you and any other JSON users,
                          previous versions (not sure if it's the same with the current one) did
                          NOT prevent recursion.

                          Let's say you had object A that had a reference to object B in it. In
                          object B, there's a reference to object A. If you "stringify" this (or
                          "encode" in the current version), a recursion error will occur. There is
                          nothing to stop JSON from simply bouncing back and forth between these
                          two objects until Flash crashes. I also had to update JSON to prevent
                          this in the following way:

                          function stringify (objectRef, used) {
                          if (used==undefined) {
                          used=new Array();
                          }
                          for (var item in used) {
                          if (used[item]==objectRef) {
                          return ('');
                          }
                          }
                          used.push(objectRef);
                          ...

                          The remainder of the function stays the same.

                          This technique is useful for any sort of function that loops back on
                          itself and where infinite recursion is a possibility. This is often
                          applicable to movie clips that have references to _parent, which refers
                          back to its children.

                          Great tool otherwise, though.

                          Patrick

                          GWD wrote:
                          > Well it seems like no matter what you could find a way to work with it directly
                          > in flash.
                          > I found the link to the one I used its here:
                          >
                          >
                          > http://www.5etdemi.com/blog/archives/2006/05/cinqetdemijson-a-better-json-parser
                          > -for-as2-suited-for-config-files/
                          >
                          > JSON.as is the file with the class you need for decoding directly in flash.
                          > And the issue I had with PHP json_encode content was the \x single hex encoded
                          > char value
                          >
                          > \u worked for utf/double byte but \x wasn't implemented in this
                          > decoder/encoder -which isn't surprising because it looks like its not part of
                          > the JSON standard. But I was receiving this for something from php... can't
                          > remember exactly what or why. After observing it I just patched the class file
                          > to include it and all was well.
                          >
                          > If you strike the same issue then you can fix it by including this additional
                          > case clause in the private function str - this is for decoding. I didn't need
                          > the encoding part so didn't try to implement this change in the 'stringify'
                          > function
                          >
                          >
                          >
                          >
                          > case 'x':
                          > u = 0;
                          > for (i = 0; i < 2; i += 1) {
                          > t = parseInt(this.next(), 16);
                          > if (!isFinite(t)) {
                          > outer = true;
                          > break;
                          > }
                          > u = u * 16 + t;
                          > }
                          > if(outer) {
                          > outer = false;
                          > break;
                          > }
                          >
                          > s += String.fromCharCode(u);
                          > break;
                          >

                          --
                          http://www.baynewmedia.com
                          Faster, easier, better...ActionScript development taken to new heights.
                          Download the BNMAPI today. You'll wonder how you ever did without it!
                          Available for ActionScript 2.0/3.0.