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
|
---
title: JSON.parse()
slug: Web/JavaScript/Reference/Global_Objects/JSON/parse
tags:
- ECMAScript 5
- JSON
- JavaScript
- Method
- Reference
- メソッド
browser-compat: javascript.builtins.JSON.parse
translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse
---
<div>{{JSRef}}</div>
<p><span class="seoSummary"><strong><code>JSON.parse()</code></strong> メソッドは文字列を JSON として解析し、文字列によって記述されている JavaScript の値やオブジェクトを構築します。任意の <strong>reviver</strong> 関数で、生成されたオブジェクトが返される前に変換を実行することができます。</span></p>
<div>{{EmbedInteractiveExample("pages/js/json-parse.html")}}</div>
<h2 id="Syntax">構文</h2>
<pre class="brush: js">
JSON.parse(text)
JSON.parse(text, reviver)
</pre>
<h3 id="Parameters">引数</h3>
<dl>
<dt><code><var>text</var></code></dt>
<dd>JSON として解析する文字列。JSON の構文の説明は {{jsxref("JSON")}} オブジェクトを参照してください。</dd>
<dt><code><var>reviver</var></code> {{optional_inline}}</dt>
<dd>もし関数である場合、解析により作り出された元の値を、オブジェクトを返す前に変換する方法を指示します。</dd>
</dl>
<h3 id="Return_value">返値</h3>
<p>{{jsxref("Object")}}, {{jsxref("Array")}}, 文字列, 数値, 論理値, null 値のいずれかで、指定された JSON の <code><var>text</var></code> に対応する値です。</p>
<h3 id="Exceptions">例外</h3>
<p>解析する文字列が有効な JSON でない場合、{{jsxref("SyntaxError")}} 例外が発生します。</p>
<h2 id="Polyfill">ポリフィル</h2>
<pre class="brush: js">// From https://github.com/douglascrockford/JSON-js/blob/master/json2.js
if (typeof JSON.parse !== "function") {
var rx_one = /^[\],:{}\s]*$/;
var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function(text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k;
var v;
var value = holder[key];
if (value && typeof value === "object") {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
rx_dangerous.lastIndex = 0;
if (rx_dangerous.test(text)) {
text = text.replace(rx_dangerous, function(a) {
return (
"\\u" +
("0000" + a.charCodeAt(0).toString(16)).slice(-4)
);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with "()" and "new"
// because they can cause invocation, and "=" because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
// replace all simple value tokens with "]" characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or "]" or
// "," or ":" or "{" or "}". If that is so, then the text is safe for eval.
if (
rx_one.test(
text
.replace(rx_two, "@")
.replace(rx_three, "]")
.replace(rx_four, "")
)
) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The "{" operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval("(" + text + ")");
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return (typeof reviver === "function") ?
walk({
"": j
}, "") :
j;
}
// If the text is not JSON parsable, then a SyntaxError is thrown.
throw new SyntaxError("JSON.parse");
};
}</pre>
<h2 id="Examples">例</h2>
<h3 id="Using_JSON.parse">JSON.parse() の使用</h3>
<pre class="brush: js">JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
</pre>
<h3 id="Using_the_reviver_parameter">reviver 引数の使用</h3>
<p><code><var>reviver</var></code> が指定された場合、解析によって計算された値は、返却される前に<em>変換</em>されます。具体的には、計算された値とそのすべてのプロパティ (最も深いプロパティから始まり、元の値自身に至るまで) は、個別に <code><var>reviver</var></code> を通して変換されます。そして、処理されるプロパティを含むオブジェクトを <code>this</code> とし、プロパティ名を文字列、プロパティ値を引数にして、これが呼び出されます。もし <code><var>reviver</var></code> 関数が {{jsxref("undefined")}} を返した場合 (または、値を返さなかった場合、例えば関数の途中で実行が中断された場合など)、そのプロパティはオブジェクトから削除されます。そうでなければそのプロパティは返値として再定義されます。</p>
<p>もし <code><var>reviver</var></code> が一部の値だけを変換して他を変換しないのであれば、必ずすべての変換されない値をそのまま返すようにしてください。そうしなければ、結果として得られるオブジェクトから削除されてしまいます。</p>
<pre class="brush: js">JSON.parse('{"p": 5}', (key, value) =>
typeof value === 'number'
? value * 2 // 数値ならば値の2倍を返す
: value // それ以外ならば変更しない
);
// { p: 10 }
JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
console.log(key); // 現在のプロパティ名を出力する。最後は ""。
return value; // 変更されていないプロパティの値を返す。
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
</pre>
<h3 id="JSON.parse_does_not_allow_trailing_commas">JSON.parse() は末尾のカンマを許容しない</h3>
<pre class="brush: js example-bad">// 両方とも SyntaxError が発生
JSON.parse('[1, 2, 3, 4, ]');
JSON.parse('{"foo" : 1, }');
</pre>
<h3 id="JSON.parse_does_not_allow_single_quotes">JSON.parse() は単一引用符を許容しない</h3>
<pre class="example-bad brush: js example-bad notranslate">// SyntaxError が発生
JSON.parse("{'foo': 1}");
</pre>
<h2 id="Specifications">仕様書</h2>
{{Specifications}}
<h2 id="Browser_compatibility">ブラウザーの互換性</h2>
<p>{{Compat}}</p>
<h2 id="See_also">関連情報</h2>
<ul>
<li>{{jsxref("JSON.stringify()")}}</li>
</ul>
|