views:

320

answers:

2

Hi,

I'm using json2.js for this:

            var str = '{"elements":[{"text": "", "colour": "#66AA50", "type": "line"}]}';
            var obj = JSON.parse(str);
            var str2 = JSON.stringify(obj);
            var obj2 = JSON.parse(str2);

Weird thing is that obj2 is a broken version of obj, i.e it's not identical to it.

In my case obj2 has only one field, named elements which is set to string

"[{"text": "", "colour": "#66AA50", "type": "line"}]"

Tested in FF 3.0.14

The following scenario works fine if implemented via Prototype's .toJSON() / .evalJSON()

Is there something wrong with my code or JSON library?

Thanks!

+1  A: 

Works for me (FF3.5)

var str = '{"elements":[{"text": "", "colour": "#66AA50", "type": "line"}]}';
            var obj = JSON.parse(str);
            var str2 = JSON.stringify(obj);
            var obj2 = JSON.parse(str2);

Equals = function(a,b)
{
  //Check if the arrays are undefined/null
  if(!a || !b)
    return false;

  //first compare their lengths
  if(a.length == b.length)
  {
    //go thru all the vars
    for(var i = 0; i < a.length;i++)
    {
      //if the var is an array, we need to make a recursive check
      //otherwise we'll just compare the values
      if(typeof a[i] == 'object') {
        if(!Equals(a[i],b[i]))
          return false;
      }
      else if(a[i] != b[i])
        return false;
    }
    return true;
  }
  else return false;
}

alert (Equals (obj,obj2)); //true
alert (JSON.stringify(obj) == JSON.stringify(obj2)); //true
alert (obj == obj2); //false (different pointer)
Ghommey
A: 

I'm not seeing the behavior you mention either. Since I have Firefox 3.5.3, which has a native version of the JSON object, I grabbed the latest json2.js (has 2009-08-17 in the source file) and modified the source to create a JSON2 object instead of a JSON object. The library is build to not override an existing JSON implementation. Also, I could compare the library code to the native Firefox code.

I stepped through the following code and didn't see elements listed as a string. Can you add a comment with the date inside the version of json2.js you have?

var str = '{"elements":[{"text": "", "colour": "#66AA50", "type": "line"}]}';
var obj = JSON.parse(str);
var str2 = JSON.stringify(obj);
var obj2 = JSON.parse(str2);

var obj3 = JSON2.parse(str);
var str3 = JSON2.stringify(obj3);
var obj4 = JSON2.parse(str3);
Kevin Hakanson