JavaScript JSON stringify()メソッド
例
JavaScriptオブジェクトを文字列化します。
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON =
JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
以下の「自分で試してみてください」の例をもっと見てください。
定義と使用法
JSON.stringify()メソッドは、JavaScriptオブジェクトを文字列に変換します。
Webサーバーにデータを送信する場合、データは文字列である必要があります。
ブラウザのサポート
表の数字は、このメソッドを完全にサポートする最初のブラウザバージョンを示しています。
Method | |||||
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
構文
JSON.stringify(obj, replacer, space)
パラメータ値
Parameter | Description |
---|---|
obj | Required. The value to convert to a string |
replacer | Optional. Either a function or an array used to transform the result. The replacer is called for each item. |
space | Optional. Either a String or a Number. A string to be used as white space (max 10 characters), or a Number, from 0 to 10, to indicate how many space characters to use as white space. |
技術的な詳細
戻り値: | 文字列 |
---|---|
JavaScriptバージョン: | ECMAScript 5 |
その他の例
例
置換機能の使用:
/*replace the value of "city" to upper case:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj, function
(key, value) {
if (key == "city") {
return value.toUpperCase();
} else {
return value;
}
});
例
スペースパラメータの使用:
/*Insert
10 space characters for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, 10);
例
スペースパラメータの使用:
/*Insert
the word SPACE for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, "SPACE");
関連ページ
JSONチュートリアル:JSONの紹介