Problem when using json2.js

Jul 7, 2011 at 10:17 PM
Edited Jul 8, 2011 at 12:42 AM

If I do the following:

var original = {};
original.Foo = 'bar';
original.Fizz = 'buzz';
assert.areEqual('buzz', original.Fizz);
console.trace('Type of original.Fizz = ' + (typeof original.Fizz));
var jsonString = JSON.stringify(original);
console.trace(jsonString);
assert.areEqual(jsonString,'{"Foo":"bar","Fizz":"buzz"}');

Then this test will fail.  The reason is that the double quotes are missing for the values buzz and bar.  I.e. what returns is this:

{"Foo":bar,"Fizz":buzz}

The only way I have to resolve this so far is by modifying the code as follows:

for (k in value) {
    if (Object.prototype.hasOwnProperty.call(value, k)) {
        v = str(k, value);

        //I added this bit, but it really just duplicates what is happening inside the call just above this
        if(typeof value[k] === 'string'){
            v = quote(value[k]);
        }

        if (v) {
            partial.push(quote(k) + (gap ? ': ' : ':') + v);
        }
    }
}

The strange thing here is that when I log what happens in the call just above my added section, it does produce the quoted strings correctly.  I can log it right before the value is returned and see "bar" but when I log 'v' above it just shows bar (no quotes).  I've followed through the json2.js code with extensive logging and it looks like it should be coming out fine, but somewhere in there it's getting altered.

ps- console.trace just calls Console.WriteLine() in C#...assert is just the assert object from YUITest, which works pretty well.

json2.js can be found here: https://github.com/douglascrockford/JSON-js