json.js revision 4515c472dc3e5ed2448a564600976759e569a0a8
1// Copyright 2009 the V8 project authors. All rights reserved. 2// Redistribution and use in source and binary forms, with or without 3// modification, are permitted provided that the following conditions are 4// met: 5// 6// * Redistributions of source code must retain the above copyright 7// notice, this list of conditions and the following disclaimer. 8// * Redistributions in binary form must reproduce the above 9// copyright notice, this list of conditions and the following 10// disclaimer in the documentation and/or other materials provided 11// with the distribution. 12// * Neither the name of Google Inc. nor the names of its 13// contributors may be used to endorse or promote products derived 14// from this software without specific prior written permission. 15// 16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 28function GenericToJSONChecks(Constructor, value, alternative) { 29 var n1 = new Constructor(value); 30 n1.valueOf = function () { return alternative; }; 31 assertEquals(alternative, n1.toJSON()); 32 var n2 = new Constructor(value); 33 n2.valueOf = null; 34 assertThrows(function () { n2.toJSON(); }, TypeError); 35 var n3 = new Constructor(value); 36 n3.valueOf = function () { return {}; }; 37 assertThrows(function () { n3.toJSON(); }, TypeError, 'result_not_primitive'); 38 var n4 = new Constructor(value); 39 n4.valueOf = function () { 40 assertEquals(0, arguments.length); 41 assertEquals(this, n4); 42 return null; 43 }; 44 assertEquals(null, n4.toJSON()); 45} 46 47// Number toJSON 48assertEquals(3, (3).toJSON()); 49assertEquals(3, (3).toJSON(true)); 50assertEquals(4, (new Number(4)).toJSON()); 51GenericToJSONChecks(Number, 5, 6); 52 53// Boolean toJSON 54assertEquals(true, (true).toJSON()); 55assertEquals(true, (true).toJSON(false)); 56assertEquals(false, (false).toJSON()); 57assertEquals(true, (new Boolean(true)).toJSON()); 58GenericToJSONChecks(Boolean, true, false); 59GenericToJSONChecks(Boolean, false, true); 60 61// String toJSON 62assertEquals("flot", "flot".toJSON()); 63assertEquals("flot", "flot".toJSON(3)); 64assertEquals("tolf", (new String("tolf")).toJSON()); 65GenericToJSONChecks(String, "x", "y"); 66 67// Date toJSON 68assertEquals("1970-01-01T00:00:00.000Z", new Date(0).toJSON()); 69assertEquals("1979-01-11T08:00:00.000Z", new Date("1979-01-11 08:00 GMT").toJSON()); 70assertEquals("2005-05-05T05:05:05.000Z", new Date("2005-05-05 05:05:05 GMT").toJSON()); 71var n1 = new Date(10000); 72n1.toISOString = function () { return "foo"; }; 73assertEquals("foo", n1.toJSON()); 74var n2 = new Date(10001); 75n2.toISOString = null; 76assertThrows(function () { n2.toJSON(); }, TypeError); 77var n3 = new Date(10002); 78n3.toISOString = function () { return {}; }; 79assertThrows(function () { n3.toJSON(); }, TypeError, "result_not_primitive"); 80var n4 = new Date(10003); 81n4.toISOString = function () { 82 assertEquals(0, arguments.length); 83 assertEquals(this, n4); 84 return null; 85}; 86assertEquals(null, n4.toJSON()); 87 88assertEquals(Object.prototype, JSON.__proto__); 89assertEquals("[object JSON]", Object.prototype.toString.call(JSON)); 90 91// DontEnum 92for (var p in this) 93 assertFalse(p == "JSON"); 94 95// Parse 96assertEquals({}, JSON.parse("{}")); 97assertEquals({42:37}, JSON.parse('{"42":37}')); 98assertEquals(null, JSON.parse("null")); 99assertEquals(true, JSON.parse("true")); 100assertEquals(false, JSON.parse("false")); 101assertEquals("foo", JSON.parse('"foo"')); 102assertEquals("f\no", JSON.parse('"f\\no"')); 103assertEquals("\b\f\n\r\t\"\u2028\/\\", 104 JSON.parse('"\\b\\f\\n\\r\\t\\"\\u2028\\/\\\\"')); 105assertEquals([1.1], JSON.parse("[1.1]")); 106assertEquals([1], JSON.parse("[1.0]")); 107 108assertEquals(0, JSON.parse("0")); 109assertEquals(1, JSON.parse("1")); 110assertEquals(0.1, JSON.parse("0.1")); 111assertEquals(1.1, JSON.parse("1.1")); 112assertEquals(1.1, JSON.parse("1.100000")); 113assertEquals(1.111111, JSON.parse("1.111111")); 114assertEquals(-0, JSON.parse("-0")); 115assertEquals(-1, JSON.parse("-1")); 116assertEquals(-0.1, JSON.parse("-0.1")); 117assertEquals(-1.1, JSON.parse("-1.1")); 118assertEquals(-1.1, JSON.parse("-1.100000")); 119assertEquals(-1.111111, JSON.parse("-1.111111")); 120assertEquals(11, JSON.parse("1.1e1")); 121assertEquals(11, JSON.parse("1.1e+1")); 122assertEquals(0.11, JSON.parse("1.1e-1")); 123assertEquals(11, JSON.parse("1.1E1")); 124assertEquals(11, JSON.parse("1.1E+1")); 125assertEquals(0.11, JSON.parse("1.1E-1")); 126 127assertEquals([], JSON.parse("[]")); 128assertEquals([1], JSON.parse("[1]")); 129assertEquals([1, "2", true, null], JSON.parse('[1, "2", true, null]')); 130 131assertEquals("", JSON.parse('""')); 132assertEquals(["", "", -0, ""], JSON.parse('[ "" , "" , -0, ""]')); 133assertEquals("", JSON.parse('""')); 134 135 136function GetFilter(name) { 137 function Filter(key, value) { 138 return (key == name) ? undefined : value; 139 } 140 return Filter; 141} 142 143var pointJson = '{"x": 1, "y": 2}'; 144assertEquals({'x': 1, 'y': 2}, JSON.parse(pointJson)); 145assertEquals({'x': 1}, JSON.parse(pointJson, GetFilter('y'))); 146assertEquals({'y': 2}, JSON.parse(pointJson, GetFilter('x'))); 147assertEquals([1, 2, 3], JSON.parse("[1, 2, 3]")); 148assertEquals([1, undefined, 3], JSON.parse("[1, 2, 3]", GetFilter(1))); 149assertEquals([1, 2, undefined], JSON.parse("[1, 2, 3]", GetFilter(2))); 150 151function DoubleNumbers(key, value) { 152 return (typeof value == 'number') ? 2 * value : value; 153} 154 155var deepObject = '{"a": {"b": 1, "c": 2}, "d": {"e": {"f": 3}}}'; 156assertEquals({"a": {"b": 1, "c": 2}, "d": {"e": {"f": 3}}}, 157 JSON.parse(deepObject)); 158assertEquals({"a": {"b": 2, "c": 4}, "d": {"e": {"f": 6}}}, 159 JSON.parse(deepObject, DoubleNumbers)); 160 161function TestInvalid(str) { 162 assertThrows(function () { JSON.parse(str); }, SyntaxError); 163} 164 165TestInvalid('abcdef'); 166TestInvalid('isNaN()'); 167TestInvalid('{"x": [1, 2, deepObject]}'); 168TestInvalid('[1, [2, [deepObject], 3], 4]'); 169TestInvalid('function () { return 0; }'); 170 171TestInvalid("[1, 2"); 172TestInvalid('{"x": 3'); 173 174// JavaScript number literals not valid in JSON. 175TestInvalid('[01]'); 176TestInvalid('[.1]'); 177TestInvalid('[1.]'); 178TestInvalid('[1.e1]'); 179TestInvalid('[-.1]'); 180TestInvalid('[-1.]'); 181 182// Plain invalid number literals. 183TestInvalid('-'); 184TestInvalid('--1'); 185TestInvalid('-1e'); 186TestInvalid('1e--1]'); 187TestInvalid('1e+-1'); 188TestInvalid('1e-+1'); 189TestInvalid('1e++1'); 190 191// JavaScript string literals not valid in JSON. 192TestInvalid("'single quote'"); // Valid JavaScript 193TestInvalid('"\\a invalid escape"'); 194TestInvalid('"\\v invalid escape"'); // Valid JavaScript 195TestInvalid('"\\\' invalid escape"'); // Valid JavaScript 196TestInvalid('"\\x42 invalid escape"'); // Valid JavaScript 197TestInvalid('"\\u202 invalid escape"'); 198TestInvalid('"\\012 invalid escape"'); 199TestInvalid('"Unterminated string'); 200TestInvalid('"Unterminated string\\"'); 201TestInvalid('"Unterminated string\\\\\\"'); 202 203// Test bad JSON that would be good JavaScript (ES5). 204 205TestInvalid("{true:42}"); 206TestInvalid("{false:42}"); 207TestInvalid("{null:42}"); 208TestInvalid("{'foo':42}"); 209TestInvalid("{42:42}"); 210TestInvalid("{0:42}"); 211TestInvalid("{-1:42}"); 212 213// Test for trailing garbage detection. 214 215TestInvalid('42 px'); 216TestInvalid('42 .2'); 217TestInvalid('42 2'); 218TestInvalid('42 e1'); 219TestInvalid('"42" ""'); 220TestInvalid('"42" ""'); 221TestInvalid('"" ""'); 222TestInvalid('true ""'); 223TestInvalid('false ""'); 224TestInvalid('null ""'); 225TestInvalid('null ""'); 226TestInvalid('[] ""'); 227TestInvalid('[true] ""'); 228TestInvalid('{} ""'); 229TestInvalid('{"x":true} ""'); 230TestInvalid('"Garbage""After string"'); 231 232// Stringify 233 234assertEquals("true", JSON.stringify(true)); 235assertEquals("false", JSON.stringify(false)); 236assertEquals("null", JSON.stringify(null)); 237assertEquals("false", JSON.stringify({toJSON: function () { return false; }})); 238assertEquals("4", JSON.stringify(4)); 239assertEquals('"foo"', JSON.stringify("foo")); 240assertEquals("null", JSON.stringify(Infinity)); 241assertEquals("null", JSON.stringify(-Infinity)); 242assertEquals("null", JSON.stringify(NaN)); 243assertEquals("4", JSON.stringify(new Number(4))); 244assertEquals('"bar"', JSON.stringify(new String("bar"))); 245 246assertEquals('"foo\\u0000bar"', JSON.stringify("foo\0bar")); 247assertEquals('"f\\"o\'o\\\\b\\ba\\fr\\nb\\ra\\tz"', 248 JSON.stringify("f\"o\'o\\b\ba\fr\nb\ra\tz")); 249 250assertEquals("[1,2,3]", JSON.stringify([1, 2, 3])); 251assertEquals("[\n 1,\n 2,\n 3\n]", JSON.stringify([1, 2, 3], null, 1)); 252assertEquals("[\n 1,\n 2,\n 3\n]", JSON.stringify([1, 2, 3], null, 2)); 253assertEquals("[\n 1,\n 2,\n 3\n]", 254 JSON.stringify([1, 2, 3], null, new Number(2))); 255assertEquals("[\n^1,\n^2,\n^3\n]", JSON.stringify([1, 2, 3], null, "^")); 256assertEquals("[\n^1,\n^2,\n^3\n]", 257 JSON.stringify([1, 2, 3], null, new String("^"))); 258assertEquals("[\n 1,\n 2,\n [\n 3,\n [\n 4\n ],\n 5\n ],\n 6,\n 7\n]", 259 JSON.stringify([1, 2, [3, [4], 5], 6, 7], null, 1)); 260assertEquals("[]", JSON.stringify([], null, 1)); 261assertEquals("[1,2,[3,[4],5],6,7]", 262 JSON.stringify([1, 2, [3, [4], 5], 6, 7], null)); 263assertEquals("[2,4,[6,[8],10],12,14]", 264 JSON.stringify([1, 2, [3, [4], 5], 6, 7], DoubleNumbers)); 265 266var circular = [1, 2, 3]; 267circular[2] = circular; 268assertThrows(function () { JSON.stringify(circular); }, TypeError); 269 270var singleton = []; 271var multiOccurrence = [singleton, singleton, singleton]; 272assertEquals("[[],[],[]]", JSON.stringify(multiOccurrence)); 273 274assertEquals('{"x":5,"y":6}', JSON.stringify({x:5,y:6})); 275assertEquals('{"x":5}', JSON.stringify({x:5,y:6}, ['x'])); 276assertEquals('{\n "a": "b",\n "c": "d"\n}', 277 JSON.stringify({a:"b",c:"d"}, null, 1)); 278assertEquals('{"y":6,"x":5}', JSON.stringify({x:5,y:6}, ['y', 'x'])); 279 280assertEquals(undefined, JSON.stringify(undefined)); 281assertEquals(undefined, JSON.stringify(function () { })); 282 283TestInvalid('1); throw "foo"; (1'); 284 285var x = 0; 286eval("(1); x++; (1)"); 287TestInvalid('1); x++; (1'); 288