ฟังก์ชัน JSON.parse() แปลง สตริง JSON ให้กลายเป็นค่า/ออบเจกต์ JavaScript
ไวยากรณ์
JSON.parse(text[, reviver])
ตัวอย่าง
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var jsonSample = '{"Tutorial": "Java", "Version": 8}'; var jsonObj = JSON.parse(jsonSample); document.write("ชื่อบทเรียน: " + jsonObj.Tutorial); document.write("<br>"); document.write("เวอร์ชัน: " + jsonObj.Version); </script> </body> </html>
ผลลัพธ์
ชื่อบทเรียน: Java เวอร์ชัน: 8
พารามิเตอร์:
text: สตริง JSON ที่ถูกต้อง (valid JSON)reviver(optional): ฟังก์ชันแปลงค่าก่อนคืนผล (เช่น แปลงวันที่)
ตัวอย่าง Reviver:
const json = '{"date": "2024-01-15T10:00:00.000Z"}';
const obj = JSON.parse(json, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(obj.date instanceof Date); // true
ข้อผิดพลาดที่พบบ่อย:
- SyntaxError: JSON ไม่ถูกต้อง (single quotes, trailing comma, comments)
- JSON ต้องใช้ double quotes เสมอ
- ใช้
JSON.parse()กับข้อมูลจาก API/Server เสมอ
คู่กับ stringify:
const obj = {a: 1};
const str = JSON.stringify(obj); // '{"a":1}'
const copy = JSON.parse(str); // {a: 1}