ใช้ substring() ตัดเครื่องหมายคำพูดนอกสุด แล้ว replace() แทนที่เครื่องหมายคำพูดคู่ แล้ว JSON.parse()
ตัวอย่างโค้ด
var studentDetails = `"{\"name\": \"John\",\"subjectName\": \"Introduction To JavaScript\"}"`;
console.log("The actual object=");
console.log(studentDetails);
var removeFirstAndLast = studentDetails.substring(1, studentDetails.length - 1);
var removeDoubleQuotes = removeFirstAndLast.replace(/""/gi, '"');
console.log(removeDoubleQuotes);
var output = JSON.parse(removeDoubleQuotes);
console.log(output);
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo103.js)
ผลลัพธ์
The actual object= "{\"name\": \"John\",\"subjectName\": \"Introduction To JavaScript\"}"
{"name": "John","subjectName": "Introduction To JavaScript"}
{ name: 'John', subjectName: 'Introduction To JavaScript' }