ใช้ JSON.stringify(obj, null, indent) พารามิเตอร์ที่ 3 คือจำนวน Space Indent
ตัวอย่างโค้ด
var details = {
studentId: 101,
studentFirstName: 'David',
studentLastName: 'Miller',
studentAge: 21,
subjectDetails: {
subjectId: 'JavaScript_101',
subjectName: 'Introduction to JavaScript'
}
};
console.log("Not Pretty JSON Format=");
console.log(JSON.stringify(details));
console.log("Pretty JSON Format=");
console.log(JSON.stringify(details, null, 3));
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo127.js)
ผลลัพธ์
Not Pretty JSON Format=
{"studentId":101,"studentFirstName":"David","studentLastName":"Miller","studentAge":21,"subjectDetails":{"subjectId":"JavaScript_101","subjectName":"Introduction to JavaScript"}}
Pretty JSON Format=
{
"studentId": 101,
"studentFirstName": "David",
"studentLastName": "Miller",
"studentAge": 21,
"subjectDetails": {
"subjectId": "JavaScript_101",
"subjectName": "Introduction to JavaScript"
}
}