blob: 945b66249bff5729cad431d3a5c8eadf39e1ca9a [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// 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
Leon Clarkee46be812010-01-19 14:06:41 +000068assertEquals("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());
Steve Blocka7e24c12009-10-30 11:49:00 +000071var 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
Ben Murdoch3bec4d22010-07-22 14:51:16 +010088assertTrue(Object.prototype === JSON.__proto__);
Steve Blocka7e24c12009-10-30 11:49:00 +000089assertEquals("[object JSON]", Object.prototype.toString.call(JSON));
90
91// DontEnum
92for (var p in this)
93 assertFalse(p == "JSON");
94
95// Parse
Steve Blocka7e24c12009-10-30 11:49:00 +000096assertEquals({}, JSON.parse("{}"));
Leon Clarke4515c472010-02-03 11:58:03 +000097assertEquals({42:37}, JSON.parse('{"42":37}'));
Steve Blocka7e24c12009-10-30 11:49:00 +000098assertEquals(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"'));
Leon Clarke4515c472010-02-03 11:58:03 +0000103assertEquals("\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"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000111assertEquals(1.1, JSON.parse("1.1"));
Leon Clarke4515c472010-02-03 11:58:03 +0000112assertEquals(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
Steve Blocka7e24c12009-10-30 11:49:00 +0000127assertEquals([], JSON.parse("[]"));
128assertEquals([1], JSON.parse("[1]"));
129assertEquals([1, "2", true, null], JSON.parse('[1, "2", true, null]'));
130
Leon Clarke4515c472010-02-03 11:58:03 +0000131assertEquals("", JSON.parse('""'));
132assertEquals(["", "", -0, ""], JSON.parse('[ "" , "" , -0, ""]'));
133assertEquals("", JSON.parse('""'));
134
135
Steve Blocka7e24c12009-10-30 11:49:00 +0000136function 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
Leon Clarke4515c472010-02-03 11:58:03 +0000174// 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
Andrei Popescu31002712010-02-23 13:46:05 +0000203// JavaScript RegExp literals not valid in JSON.
204TestInvalid('/true/');
Leon Clarke4515c472010-02-03 11:58:03 +0000205
Andrei Popescu31002712010-02-23 13:46:05 +0000206// Test bad JSON that would be good JavaScript (ES5).
Leon Clarke4515c472010-02-03 11:58:03 +0000207TestInvalid("{true:42}");
208TestInvalid("{false:42}");
209TestInvalid("{null:42}");
210TestInvalid("{'foo':42}");
211TestInvalid("{42:42}");
212TestInvalid("{0:42}");
213TestInvalid("{-1:42}");
214
215// Test for trailing garbage detection.
Leon Clarke4515c472010-02-03 11:58:03 +0000216TestInvalid('42 px');
217TestInvalid('42 .2');
218TestInvalid('42 2');
219TestInvalid('42 e1');
220TestInvalid('"42" ""');
221TestInvalid('"42" ""');
222TestInvalid('"" ""');
223TestInvalid('true ""');
224TestInvalid('false ""');
225TestInvalid('null ""');
226TestInvalid('null ""');
227TestInvalid('[] ""');
228TestInvalid('[true] ""');
229TestInvalid('{} ""');
230TestInvalid('{"x":true} ""');
231TestInvalid('"Garbage""After string"');
232
Steve Blocka7e24c12009-10-30 11:49:00 +0000233// Stringify
234
235assertEquals("true", JSON.stringify(true));
236assertEquals("false", JSON.stringify(false));
237assertEquals("null", JSON.stringify(null));
238assertEquals("false", JSON.stringify({toJSON: function () { return false; }}));
239assertEquals("4", JSON.stringify(4));
240assertEquals('"foo"', JSON.stringify("foo"));
241assertEquals("null", JSON.stringify(Infinity));
242assertEquals("null", JSON.stringify(-Infinity));
243assertEquals("null", JSON.stringify(NaN));
244assertEquals("4", JSON.stringify(new Number(4)));
245assertEquals('"bar"', JSON.stringify(new String("bar")));
246
247assertEquals('"foo\\u0000bar"', JSON.stringify("foo\0bar"));
248assertEquals('"f\\"o\'o\\\\b\\ba\\fr\\nb\\ra\\tz"',
249 JSON.stringify("f\"o\'o\\b\ba\fr\nb\ra\tz"));
250
251assertEquals("[1,2,3]", JSON.stringify([1, 2, 3]));
252assertEquals("[\n 1,\n 2,\n 3\n]", JSON.stringify([1, 2, 3], null, 1));
253assertEquals("[\n 1,\n 2,\n 3\n]", JSON.stringify([1, 2, 3], null, 2));
254assertEquals("[\n 1,\n 2,\n 3\n]",
255 JSON.stringify([1, 2, 3], null, new Number(2)));
256assertEquals("[\n^1,\n^2,\n^3\n]", JSON.stringify([1, 2, 3], null, "^"));
257assertEquals("[\n^1,\n^2,\n^3\n]",
258 JSON.stringify([1, 2, 3], null, new String("^")));
259assertEquals("[\n 1,\n 2,\n [\n 3,\n [\n 4\n ],\n 5\n ],\n 6,\n 7\n]",
260 JSON.stringify([1, 2, [3, [4], 5], 6, 7], null, 1));
261assertEquals("[]", JSON.stringify([], null, 1));
262assertEquals("[1,2,[3,[4],5],6,7]",
263 JSON.stringify([1, 2, [3, [4], 5], 6, 7], null));
264assertEquals("[2,4,[6,[8],10],12,14]",
265 JSON.stringify([1, 2, [3, [4], 5], 6, 7], DoubleNumbers));
266
267var circular = [1, 2, 3];
268circular[2] = circular;
269assertThrows(function () { JSON.stringify(circular); }, TypeError);
270
271var singleton = [];
272var multiOccurrence = [singleton, singleton, singleton];
273assertEquals("[[],[],[]]", JSON.stringify(multiOccurrence));
274
275assertEquals('{"x":5,"y":6}', JSON.stringify({x:5,y:6}));
276assertEquals('{"x":5}', JSON.stringify({x:5,y:6}, ['x']));
277assertEquals('{\n "a": "b",\n "c": "d"\n}',
278 JSON.stringify({a:"b",c:"d"}, null, 1));
279assertEquals('{"y":6,"x":5}', JSON.stringify({x:5,y:6}, ['y', 'x']));
280
Andrei Popescu31002712010-02-23 13:46:05 +0000281// The gap is capped at ten characters if specified as string.
282assertEquals('{\n "a": "b",\n "c": "d"\n}',
283 JSON.stringify({a:"b",c:"d"}, null,
284 " /*characters after 10th*/"));
285
286//The gap is capped at ten characters if specified as number.
287assertEquals('{\n "a": "b",\n "c": "d"\n}',
288 JSON.stringify({a:"b",c:"d"}, null, 15));
289
290// Replaced wrapped primitives are unwrapped.
291function newx(k, v) { return (k == "x") ? new v(42) : v; }
292assertEquals('{"x":"42"}', JSON.stringify({x: String}, newx));
293assertEquals('{"x":42}', JSON.stringify({x: Number}, newx));
294assertEquals('{"x":true}', JSON.stringify({x: Boolean}, newx));
295
Steve Blocka7e24c12009-10-30 11:49:00 +0000296assertEquals(undefined, JSON.stringify(undefined));
297assertEquals(undefined, JSON.stringify(function () { }));
Andrei Popescu31002712010-02-23 13:46:05 +0000298// Arrays with missing, undefined or function elements have those elements
299// replaced by null.
300assertEquals("[null,null,null]",
301 JSON.stringify([undefined,,function(){}]));
302
303// Objects with undefined or function properties (including replaced properties)
304// have those properties ignored.
305assertEquals('{}',
306 JSON.stringify({a: undefined, b: function(){}, c: 42, d: 42},
307 function(k, v) { if (k == "c") return undefined;
308 if (k == "d") return function(){};
309 return v; }));
Steve Blocka7e24c12009-10-30 11:49:00 +0000310
Leon Clarke4515c472010-02-03 11:58:03 +0000311TestInvalid('1); throw "foo"; (1');
Steve Blocka7e24c12009-10-30 11:49:00 +0000312
313var x = 0;
314eval("(1); x++; (1)");
Leon Clarke4515c472010-02-03 11:58:03 +0000315TestInvalid('1); x++; (1');
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100316
317// Test string conversion of argument.
318var o = { toString: function() { return "42"; } };
319assertEquals(42, JSON.parse(o));