Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Định dạng (pretty print) JSON string trong JavaScript

Dùng JSON.stringify(obj, replacer, space) với tham số space (số space hoặc string) để format đẹp.

Ví dụ


var data = {
    studentId: 101,
    studentFirstName: 'David',
    studentLastName: 'Miller',
    studentAge: 21,
    subjectDetails: {
        subjectId: 'JavaScript_101',
        subjectName: 'Introduction to JavaScript'
    }
};

console.log("Compact:", JSON.stringify(data));
console.log("Pretty (3 spaces):", JSON.stringify(data, null, 3));
console.log("Pretty (tab):", JSON.stringify(data, null, '\t'));

Cách chạy

node demo.js

Kết quả


Compact: {"studentId":101,"studentFirstName":"David",...}
Pretty (3 spaces): {
   "studentId": 101,
   "studentFirstName": "David",
   "studentLastName": "Miller",
   "studentAge": 21,
   "subjectDetails": {
      "subjectId": "JavaScript_101",
      "subjectName": "Introduction to JavaScript"
   }
}

Tham số:

  • replacer: function/array lọc key (null = không lọc)
  • space: number (0-10) hoặc string (max 10 chars) cho indentation

Ứng dụng: Debug, log, lưu file config, response API đẹp.