Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน JSON.stringify() ใน JavaScript

ฟังก์ชัน JSON.stringify() แปลงค่า JavaScript (object, array, primitive) ให้เป็น สตริง JSON เพื่อส่งผ่านเครือข่ายหรือเก็บในที่เก็บข้อมูล

ไวยากรณ์

JSON.stringify(value[, replacer[, space]])

ตัวอย่าง

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var jsonSample = '{Tutorial: Java, Version:8}';       var jsonObj = JSON.stringify(jsonSample);       document.write(jsonObj);    </script> </body> </html>

ผลลัพธ์

"{Tutorial: Java, Version:8}"

พารามิเตอร์ทั้งหมด:

  • value: ค่าที่จะแปลง (object, array, string, number, boolean, null)
  • replacer (optional): ฟังก์ชันหรือ array กรอง property ที่จะใส่
  • space (optional): การจัดรูปแบบ (indentation) - ตัวเลขหรือสตริง

ตัวอย่างขั้นสูง:

const obj = {name: 'John', age: 30, password: 'secret'};

// ใช้ replacer กรอง password ออก
JSON.stringify(obj, (key, value) => key === 'password' ? undefined : value);
// '{"name":"John","age":30}'

// ใช้ space สำหรับ pretty print
JSON.stringify(obj, null, 2);
/*
{
  "name": "John",
  "age": 30,
  "password": "secret"
}
*/

ข้อจำกัด:

  • ไม่รองรับ: Function, undefined, Symbol, Circular reference
  • Date → ISO string, RegExp → {}, Error → {}