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 เป็นสตริง
เมื่อส่งข้อมูลไปยังเว็บเซิร์ฟเวอร์ ข้อมูลจะต้องเป็นสตริง
รองรับเบราว์เซอร์
ตัวเลขในตารางระบุเบราว์เซอร์รุ่นแรกที่รองรับวิธีการนี้อย่างเต็มที่
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. |
รายละเอียดทางเทคนิค
คืนมูลค่า: | สตริง |
---|---|
เวอร์ชันจาวาสคริปต์: | 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