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

Pretty print JSON trong JavaScript

JSON.stringify(value, replacer, space) — tham số thứ 3 space định dạng indent.

Ví dụ với object

let a = {
  name: "A",
  age: 35,
  address: { street: "32, Baker Street", city: "Chicago" }
};
console.log(JSON.stringify(a, null, 4));

Kết quả

{
    "name": "A",
    "age": 35,
    "address": {
        "street": "32, Baker Street",
        "city": "Chicago"
    }
}

Với JSON string (cần parse trước)

let jsonStr = '{"name":"A","age":35,"address":{"street":"32, Baker Street","city":"Chicago"}}';
console.log(JSON.stringify(JSON.parse(jsonStr), null, 2));

Mẹo: space có thể là string (ví dụ "\t" hoặc " ") để custom indent.