json.js revision 1e0659c275bb392c045087af4f6b0d7565cb3d77
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
28// Date toJSON
29assertEquals("1970-01-01T00:00:00.000Z", new Date(0).toJSON());
30assertEquals("1979-01-11T08:00:00.000Z", new Date("1979-01-11 08:00 GMT").toJSON());
31assertEquals("2005-05-05T05:05:05.000Z", new Date("2005-05-05 05:05:05 GMT").toJSON());
32var n1 = new Date(10000);
33n1.toISOString = function () { return "foo"; };
34assertEquals("foo", n1.toJSON());
35var n2 = new Date(10001);
36n2.toISOString = null;
37assertThrows(function () { n2.toJSON(); }, TypeError);
38var n4 = new Date(10003);
39n4.toISOString = function () {
40  assertEquals(0, arguments.length);
41  assertEquals(this, n4);
42  return null;
43};
44assertEquals(null, n4.toJSON());
45
46assertTrue(Object.prototype === JSON.__proto__);
47assertEquals("[object JSON]", Object.prototype.toString.call(JSON));
48
49//Test Date.prototype.toJSON as generic function.
50var d1 = {toJSON: Date.prototype.toJSON,
51         toISOString: function() { return 42; }};
52assertEquals(42, d1.toJSON());
53
54var d2 = {toJSON: Date.prototype.toJSON,
55          valueOf: function() { return Infinity; },
56          toISOString: function() { return 42; }};
57assertEquals(null, d2.toJSON());
58
59var d3 = {toJSON: Date.prototype.toJSON,
60          valueOf: "not callable",
61          toString: function() { return Infinity; },
62          toISOString: function() { return 42; }};
63
64assertEquals(null, d3.toJSON());
65
66var d4 = {toJSON: Date.prototype.toJSON,
67          valueOf: "not callable",
68          toString: "not callable either",
69          toISOString: function() { return 42; }};
70assertThrows("d4.toJSON()", TypeError);  // ToPrimitive throws.
71
72var d5 = {toJSON: Date.prototype.toJSON,
73          valueOf: "not callable",
74          toString: function() { return "Infinity"; },
75          toISOString: function() { return 42; }};
76assertEquals(42, d5.toJSON());
77
78var d6 = {toJSON: Date.prototype.toJSON,
79          toISOString: function() { return ["not primitive"]; }};
80assertEquals(["not primitive"], d6.toJSON());
81
82var d7 = {toJSON: Date.prototype.toJSON,
83          ISOString: "not callable"};
84assertThrows("d7.toJSON()", TypeError);
85
86// DontEnum
87for (var p in this) {
88  assertFalse(p == "JSON");
89}
90
91// Parse
92assertEquals({}, JSON.parse("{}"));
93assertEquals({42:37}, JSON.parse('{"42":37}'));
94assertEquals(null, JSON.parse("null"));
95assertEquals(true, JSON.parse("true"));
96assertEquals(false, JSON.parse("false"));
97assertEquals("foo", JSON.parse('"foo"'));
98assertEquals("f\no", JSON.parse('"f\\no"'));
99assertEquals("\b\f\n\r\t\"\u2028\/\\",
100             JSON.parse('"\\b\\f\\n\\r\\t\\"\\u2028\\/\\\\"'));
101assertEquals([1.1], JSON.parse("[1.1]"));
102assertEquals([1], JSON.parse("[1.0]"));
103
104assertEquals(0, JSON.parse("0"));
105assertEquals(1, JSON.parse("1"));
106assertEquals(0.1, JSON.parse("0.1"));
107assertEquals(1.1, JSON.parse("1.1"));
108assertEquals(1.1, JSON.parse("1.100000"));
109assertEquals(1.111111, JSON.parse("1.111111"));
110assertEquals(-0, JSON.parse("-0"));
111assertEquals(-1, JSON.parse("-1"));
112assertEquals(-0.1, JSON.parse("-0.1"));
113assertEquals(-1.1, JSON.parse("-1.1"));
114assertEquals(-1.1, JSON.parse("-1.100000"));
115assertEquals(-1.111111, JSON.parse("-1.111111"));
116assertEquals(11, JSON.parse("1.1e1"));
117assertEquals(11, JSON.parse("1.1e+1"));
118assertEquals(0.11, JSON.parse("1.1e-1"));
119assertEquals(11, JSON.parse("1.1E1"));
120assertEquals(11, JSON.parse("1.1E+1"));
121assertEquals(0.11, JSON.parse("1.1E-1"));
122
123assertEquals([], JSON.parse("[]"));
124assertEquals([1], JSON.parse("[1]"));
125assertEquals([1, "2", true, null], JSON.parse('[1, "2", true, null]'));
126
127assertEquals("", JSON.parse('""'));
128assertEquals(["", "", -0, ""], JSON.parse('[    ""  ,    ""  ,   -0,    ""]'));
129assertEquals("", JSON.parse('""'));
130
131
132function GetFilter(name) {
133  function Filter(key, value) {
134    return (key == name) ? undefined : value;
135  }
136  return Filter;
137}
138
139var pointJson = '{"x": 1, "y": 2}';
140assertEquals({'x': 1, 'y': 2}, JSON.parse(pointJson));
141assertEquals({'x': 1}, JSON.parse(pointJson, GetFilter('y')));
142assertEquals({'y': 2}, JSON.parse(pointJson, GetFilter('x')));
143assertEquals([1, 2, 3], JSON.parse("[1, 2, 3]"));
144assertEquals([1, undefined, 3], JSON.parse("[1, 2, 3]", GetFilter(1)));
145assertEquals([1, 2, undefined], JSON.parse("[1, 2, 3]", GetFilter(2)));
146
147function DoubleNumbers(key, value) {
148  return (typeof value == 'number') ? 2 * value : value;
149}
150
151var deepObject = '{"a": {"b": 1, "c": 2}, "d": {"e": {"f": 3}}}';
152assertEquals({"a": {"b": 1, "c": 2}, "d": {"e": {"f": 3}}},
153             JSON.parse(deepObject));
154assertEquals({"a": {"b": 2, "c": 4}, "d": {"e": {"f": 6}}},
155             JSON.parse(deepObject, DoubleNumbers));
156
157function TestInvalid(str) {
158  assertThrows(function () { JSON.parse(str); }, SyntaxError);
159}
160
161TestInvalid('abcdef');
162TestInvalid('isNaN()');
163TestInvalid('{"x": [1, 2, deepObject]}');
164TestInvalid('[1, [2, [deepObject], 3], 4]');
165TestInvalid('function () { return 0; }');
166
167TestInvalid("[1, 2");
168TestInvalid('{"x": 3');
169
170// JavaScript number literals not valid in JSON.
171TestInvalid('[01]');
172TestInvalid('[.1]');
173TestInvalid('[1.]');
174TestInvalid('[1.e1]');
175TestInvalid('[-.1]');
176TestInvalid('[-1.]');
177
178// Plain invalid number literals.
179TestInvalid('-');
180TestInvalid('--1');
181TestInvalid('-1e');
182TestInvalid('1e--1]');
183TestInvalid('1e+-1');
184TestInvalid('1e-+1');
185TestInvalid('1e++1');
186
187// JavaScript string literals not valid in JSON.
188TestInvalid("'single quote'");  // Valid JavaScript
189TestInvalid('"\\a invalid escape"');
190TestInvalid('"\\v invalid escape"');  // Valid JavaScript
191TestInvalid('"\\\' invalid escape"');  // Valid JavaScript
192TestInvalid('"\\x42 invalid escape"');  // Valid JavaScript
193TestInvalid('"\\u202 invalid escape"');
194TestInvalid('"\\012 invalid escape"');
195TestInvalid('"Unterminated string');
196TestInvalid('"Unterminated string\\"');
197TestInvalid('"Unterminated string\\\\\\"');
198
199// JavaScript RegExp literals not valid in JSON.
200TestInvalid('/true/');
201
202// Test bad JSON that would be good JavaScript (ES5).
203TestInvalid("{true:42}");
204TestInvalid("{false:42}");
205TestInvalid("{null:42}");
206TestInvalid("{'foo':42}");
207TestInvalid("{42:42}");
208TestInvalid("{0:42}");
209TestInvalid("{-1:42}");
210
211// Test for trailing garbage detection.
212TestInvalid('42 px');
213TestInvalid('42 .2');
214TestInvalid('42 2');
215TestInvalid('42 e1');
216TestInvalid('"42" ""');
217TestInvalid('"42" ""');
218TestInvalid('"" ""');
219TestInvalid('true ""');
220TestInvalid('false ""');
221TestInvalid('null ""');
222TestInvalid('null ""');
223TestInvalid('[] ""');
224TestInvalid('[true] ""');
225TestInvalid('{} ""');
226TestInvalid('{"x":true} ""');
227TestInvalid('"Garbage""After string"');
228
229// Stringify
230
231assertEquals("true", JSON.stringify(true));
232assertEquals("false", JSON.stringify(false));
233assertEquals("null", JSON.stringify(null));
234assertEquals("false", JSON.stringify({toJSON: function () { return false; }}));
235assertEquals("4", JSON.stringify(4));
236assertEquals('"foo"', JSON.stringify("foo"));
237assertEquals("null", JSON.stringify(Infinity));
238assertEquals("null", JSON.stringify(-Infinity));
239assertEquals("null", JSON.stringify(NaN));
240assertEquals("4", JSON.stringify(new Number(4)));
241assertEquals('"bar"', JSON.stringify(new String("bar")));
242
243assertEquals('"foo\\u0000bar"', JSON.stringify("foo\0bar"));
244assertEquals('"f\\"o\'o\\\\b\\ba\\fr\\nb\\ra\\tz"',
245             JSON.stringify("f\"o\'o\\b\ba\fr\nb\ra\tz"));
246
247assertEquals("[1,2,3]", JSON.stringify([1, 2, 3]));
248assertEquals("[\n 1,\n 2,\n 3\n]", JSON.stringify([1, 2, 3], null, 1));
249assertEquals("[\n  1,\n  2,\n  3\n]", JSON.stringify([1, 2, 3], null, 2));
250assertEquals("[\n  1,\n  2,\n  3\n]",
251             JSON.stringify([1, 2, 3], null, new Number(2)));
252assertEquals("[\n^1,\n^2,\n^3\n]", JSON.stringify([1, 2, 3], null, "^"));
253assertEquals("[\n^1,\n^2,\n^3\n]",
254             JSON.stringify([1, 2, 3], null, new String("^")));
255assertEquals("[\n 1,\n 2,\n [\n  3,\n  [\n   4\n  ],\n  5\n ],\n 6,\n 7\n]",
256             JSON.stringify([1, 2, [3, [4], 5], 6, 7], null, 1));
257assertEquals("[]", JSON.stringify([], null, 1));
258assertEquals("[1,2,[3,[4],5],6,7]",
259             JSON.stringify([1, 2, [3, [4], 5], 6, 7], null));
260assertEquals("[2,4,[6,[8],10],12,14]",
261             JSON.stringify([1, 2, [3, [4], 5], 6, 7], DoubleNumbers));
262
263var circular = [1, 2, 3];
264circular[2] = circular;
265assertThrows(function () { JSON.stringify(circular); }, TypeError);
266
267var singleton = [];
268var multiOccurrence = [singleton, singleton, singleton];
269assertEquals("[[],[],[]]", JSON.stringify(multiOccurrence));
270
271assertEquals('{"x":5,"y":6}', JSON.stringify({x:5,y:6}));
272assertEquals('{"x":5}', JSON.stringify({x:5,y:6}, ['x']));
273assertEquals('{\n "a": "b",\n "c": "d"\n}',
274             JSON.stringify({a:"b",c:"d"}, null, 1));
275assertEquals('{"y":6,"x":5}', JSON.stringify({x:5,y:6}, ['y', 'x']));
276
277// toJSON get string keys.
278var checker = {};
279var array = [checker];
280checker.toJSON = function(key) { return 1 + key; };
281assertEquals('["10"]', JSON.stringify(array));
282
283// The gap is capped at ten characters if specified as string.
284assertEquals('{\n          "a": "b",\n          "c": "d"\n}',
285              JSON.stringify({a:"b",c:"d"}, null,
286                             "          /*characters after 10th*/"));
287
288//The gap is capped at ten characters if specified as number.
289assertEquals('{\n          "a": "b",\n          "c": "d"\n}',
290              JSON.stringify({a:"b",c:"d"}, null, 15));
291
292// Replaced wrapped primitives are unwrapped.
293function newx(k, v)  { return (k == "x") ? new v(42) : v; }
294assertEquals('{"x":"42"}', JSON.stringify({x: String}, newx));
295assertEquals('{"x":42}', JSON.stringify({x: Number}, newx));
296assertEquals('{"x":true}', JSON.stringify({x: Boolean}, newx));
297
298assertEquals(undefined, JSON.stringify(undefined));
299assertEquals(undefined, JSON.stringify(function () { }));
300// Arrays with missing, undefined or function elements have those elements
301// replaced by null.
302assertEquals("[null,null,null]",
303             JSON.stringify([undefined,,function(){}]));
304
305// Objects with undefined or function properties (including replaced properties)
306// have those properties ignored.
307assertEquals('{}',
308             JSON.stringify({a: undefined, b: function(){}, c: 42, d: 42},
309                            function(k, v) { if (k == "c") return undefined;
310                                             if (k == "d") return function(){};
311                                             return v; }));
312
313TestInvalid('1); throw "foo"; (1');
314
315var x = 0;
316eval("(1); x++; (1)");
317TestInvalid('1); x++; (1');
318
319// Test string conversion of argument.
320var o = { toString: function() { return "42"; } };
321assertEquals(42, JSON.parse(o));
322
323
324for (var i = 0; i < 65536; i++) {
325  var string = String.fromCharCode(i);
326  var encoded = JSON.stringify(string);
327  var expected = "uninitialized";
328  // Following the ES5 specification of the abstraction function Quote.
329  if (string == '"' || string == '\\') {
330    // Step 2.a
331    expected = '\\' + string;
332  } else if ("\b\t\n\r\f".indexOf(string) >= 0) {
333    // Step 2.b
334    if (string == '\b') expected = '\\b';
335    else if (string == '\t') expected = '\\t';
336    else if (string == '\n') expected = '\\n';
337    else if (string == '\f') expected = '\\f';
338    else if (string == '\r') expected = '\\r';
339  } else if (i < 32) {
340    // Step 2.c
341    if (i < 16) {
342      expected = "\\u000" + i.toString(16);
343    } else {
344      expected = "\\u00" + i.toString(16);
345    }
346  } else {
347    expected = string;
348  }
349  assertEquals('"' + expected + '"', encoded, "Codepoint " + i);
350}
351
352
353// Ensure that wrappers and callables are handled correctly.
354var num37 = new Number(42);
355num37.valueOf = function() { return 37; };
356
357var numFoo = new Number(42);
358numFoo.valueOf = "not callable";
359numFoo.toString = function() { return "foo"; };
360
361var numTrue = new Number(42);
362numTrue.valueOf = function() { return true; }
363
364var strFoo = new String("bar");
365strFoo.toString = function() { return "foo"; };
366
367var str37 = new String("bar");
368str37.toString = "not callable";
369str37.valueOf = function() { return 37; };
370
371var strTrue = new String("bar");
372strTrue.toString = function() { return true; }
373
374var func = function() { /* Is callable */ };
375
376var funcJSON = function() { /* Is callable */ };
377funcJSON.toJSON = function() { return "has toJSON"; };
378
379var re = /Is callable/;
380
381var reJSON = /Is callable/;
382reJSON.toJSON = function() { return "has toJSON"; };
383
384assertEquals(
385    '[37,null,1,"foo","37","true",null,"has toJSON",null,"has toJSON"]',
386    JSON.stringify([num37, numFoo, numTrue,
387                    strFoo, str37, strTrue,
388                    func, funcJSON, re, reJSON]));
389
390
391var oddball = Object(42);
392oddball.__proto__ = { __proto__: null, toString: function() { return true; } };
393assertEquals('1', JSON.stringify(oddball));
394
395var getCount = 0;
396var callCount = 0;
397var counter = { get toJSON() { getCount++;
398                               return function() { callCount++;
399                                                   return 42; }; } };
400assertEquals('42', JSON.stringify(counter));
401assertEquals(1, getCount);
402assertEquals(1, callCount);
403
404var oddball2 = Object(42);
405var oddball3 = Object("foo");
406oddball3.__proto__ = { __proto__: null,
407                       toString: "not callable",
408                       valueOf: function() { return true; } };
409oddball2.__proto__ = { __proto__: null,
410                       toJSON: function () { return oddball3; } }
411assertEquals('"true"', JSON.stringify(oddball2));
412
413
414var falseNum = Object("37");
415falseNum.__proto__ = Number.prototype;
416falseNum.toString = function() { return 42; };
417assertEquals('"42"', JSON.stringify(falseNum));
418
419// We don't currently allow plain properties called __proto__ in JSON
420// objects in JSON.parse. Instead we read them as we would JS object
421// literals. If we change that, this test should change with it.
422//
423// Parse a non-object value as __proto__. This must not create a
424// __proto__ property different from the original, and should not
425// change the original.
426var o = JSON.parse('{"__proto__":5}');
427assertEquals(Object.prototype, o.__proto__);  // __proto__ isn't changed.
428assertEquals(0, Object.keys(o).length);  // __proto__ isn't added as enumerable.
429
430
431
432