aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html
blob: 98f01ef784fb9fd5117d4c30d003d37b4c79a5a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
---
title: JSON.stringify()
slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify
translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify
---
<div>{{JSRef}}</div>

<p><strong><code>JSON.stringify()</code></strong> method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.</p>

<div>{{EmbedInteractiveExample("pages/js/json-stringify.html")}}</div>

<h2 id="語法">語法</h2>

<pre class="syntaxbox"><code>JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])</code></pre>

<h3 id="參數">參數</h3>

<dl>
 <dt><code>value</code></dt>
 <dd>The value to convert to a JSON string.</dd>
 <dt><code>replacer</code> {{optional_inline}}</dt>
 <dd>A function that alters the behavior of the stringification process, or an array of {{jsxref("String")}} and {{jsxref("Number")}} objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.</dd>
 <dt><code>space</code> {{optional_inline}}</dt>
 <dd>A {{jsxref("String")}} or {{jsxref("Number")}} object that's used to insert white space into the output JSON string for readability purposes. If this is a <code>Number</code>, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a <code>String</code>, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.</dd>
</dl>

<h3 id="回傳值">回傳值</h3>

<p>A JSON string representing the given value.</p>

<h2 id="Description">Description</h2>

<p><code>JSON.stringify()</code> converts a value to JSON notation representing it:</p>

<ul>
 <li>{{jsxref("Boolean")}}, {{jsxref("Number")}}, and {{jsxref("String")}} objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.</li>
 <li>If {{jsxref("undefined")}}, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to {{jsxref("null")}} (when it is found in an array). <code>JSON.stringify</code> can also just return <code>undefined</code> when passing in "pure" values like <code>JSON.stringify(function(){})</code> or <code>JSON.stringify(undefined)</code>.</li>
 <li>All symbol-keyed properties will be completely ignored, even when using the <code>replacer</code> function.</li>
 <li>Non-enumerable properties will be ignored</li>
</ul>

<pre class="brush: js">JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
// '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}'
JSON.stringify([new Number(3), new String('false'), new Boolean(false)]);
// '[3,"false",false]'

JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });
// '{"x":[10,null,null,null]}'

// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
// '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' });
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
  if (typeof k === 'symbol') {
    return 'a symbol';
  }
});
// '{}'

// Non-enumerable properties:
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
// '{"y":"y"}'

</pre>

<h3 id="The_replacer_parameter"><a></a>The <code>replacer</code> parameter</h3>

<p>The <code>replacer</code> parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's <code>this</code> parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:</p>

<ul>
 <li>If you return a {{jsxref("Number")}}, the string corresponding to that number is used as the value for the property when added to the JSON string.</li>
 <li>If you return a {{jsxref("String")}}, that string is used as the property's value when adding it to the JSON string.</li>
 <li>If you return a {{jsxref("Boolean")}}, "true" or "false" is used as the property's value, as appropriate, when adding it to the JSON string.</li>
 <li>If you return any other object, the object is recursively stringified into the JSON string, calling the <code>replacer</code> function on each property, unless the object is a function, in which case nothing is added to the JSON string.</li>
 <li>If you return <code>undefined</code>, the property is not included (i.e., filtered out) in the output JSON string.</li>
</ul>

<div class="note"><strong>Note:</strong> You cannot use the <code>replacer</code> function to remove values from an array. If you return <code>undefined</code> or a function then <code>null</code> is used instead.</div>

<h4 id="Example_with_a_function">Example with a function</h4>

<pre class="brush: js">function replacer(key, value) {
  // Filtering out properties
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}

var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
</pre>

<h4 id="Example_with_an_array">Example with an array</h4>

<p>If <code>replacer</code> is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.</p>

<pre class="brush: js">JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', only keep "week" and "month" properties
</pre>

<h3 id="The_space_argument"><a></a>The <code>space</code> argument</h3>

<p>The <code>space</code> argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).</p>

<pre class="brush: js">JSON.stringify({ a: 2 }, null, ' ');
// '{
//  "a": 2
// }'
</pre>

<p>Using a tab character mimics standard pretty-print appearance:</p>

<pre class="brush: js">JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
//     "uno": 1,
//     "dos": 2
// }'
</pre>

<h3 id="toJSON_behavior"><code>toJSON()</code> behavior</h3>

<p>If an object being stringified has a property named <code>toJSON</code> whose value is a function, then the <code>toJSON()</code> method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the <code>toJSON()</code> method when called will be serialized. <code>JSON.stringify()</code> calls <code>toJSON</code> with one parameter:</p>

<ul>
 <li>if this object is a property value, the property name</li>
 <li>if it is in an array, the index in the array, as a string</li>
 <li>an empty string if <code>JSON.stringify()</code> was directly called on this object</li>
</ul>

<p>For example:</p>

<pre class="brush: js">const bonnie = {
  name: 'Bonnie Washington',
  age: 17,
  class: 'Year 5 Wisdom',
  isMonitor: false,
  toJSON: function(key) {
    // Clone object to prevent accidentally performing modification on the original object
    const cloneObj = { ...this };

    delete cloneObj.age;
    delete cloneObj.isMonitor;
    cloneObj.year = 5;
    cloneObj.class = 'Wisdom';

    if (key) {
      cloneObj.code = key;
    }

    return cloneObj;
  }
}

JSON.stringify(bonnie);
// Returns '{"name":"Bonnie Washington","class":"Wisdom","year":5}'

const students = {bonnie};
JSON.stringify(students);
// Returns '{"bonnie":{"name":"Bonnie Washington","class":"Wisdom","year":5,"code":"bonnie"}}'

const monitorCandidate = [bonnie];
JSON.stringify(monitorCandidate)
// Returns '[{"name":"Bonnie Washington","class":"Wisdom","year":5,"code":"0"}]'</pre>

<h3 id="Issue_with_plain_JSON.stringify_for_use_as_JavaScript">Issue with plain <code>JSON.stringify</code> for use as JavaScript</h3>

<p>Note that JSON is <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">not a completely strict subset of JavaScript</a>, with two line terminators (Line separator and Paragraph separator) not needing to be escaped in JSON but needing to be escaped in JavaScript. Therefore, if the JSON is meant to be evaluated or directly utilized within <a href="https://en.wikipedia.org/wiki/JSONP">JSONP</a>, the following utility can be used:</p>

<pre class="brush: js">function jsFriendlyJSONStringify (s) {
    return JSON.stringify(s).
        replace(/\u2028/g, '\\u2028').
        replace(/\u2029/g, '\\u2029');
}

var s = {
    a: String.fromCharCode(0x2028),
    b: String.fromCharCode(0x2029)
};
try {
    eval('(' + JSON.stringify(s) + ')');
} catch (e) {
    console.log(e); // "SyntaxError: unterminated string literal"
}

// No need for a catch
eval('(' + jsFriendlyJSONStringify(s) + ')');

// console.log in Firefox unescapes the Unicode if
//   logged to console, so we use alert
alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}</pre>

<h3 id="Example_of_using_JSON.stringify_with_localStorage">Example of using <code>JSON.stringify()</code> with <code>localStorage</code></h3>

<p>In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of <code>JSON.stringify()</code>:</p>

<div class="warning">
<p>Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like {{jsxref("Date")}} will be a string after {{jsxref("JSON.parse()")}}.</p>
</div>

<pre class="brush: js">// Creating an example of JSON
var session = {
  'screens': [],
  'state': true
};
session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });

// Converting the JSON string with JSON.stringify()
// then saving with localStorage in the name of session
localStorage.setItem('session', JSON.stringify(session));

// Example of how to transform the String generated through
// JSON.stringify() and saved in localStorage in JSON object again
var restoredSession = JSON.parse(localStorage.getItem('session'));

// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.7.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>


<p>{{Compat("javascript.builtins.JSON.stringify")}}</p>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("JSON.parse()")}}</li>
</ul>