将 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简介
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!