Làm cách nào để gọi hàm JavaScript trong JSON?

Giả sử chúng ta có một đối tượng phức tạp và chúng ta muốn chuyển đổi nó thành một chuỗi, để gửi nó qua mạng hoặc chỉ xuất nó cho mục đích ghi nhật ký

Đương nhiên, một chuỗi như vậy phải bao gồm tất cả các thuộc tính quan trọng

Chúng tôi có thể thực hiện chuyển đổi như thế này

let user = {
  name: "John",
  age: 30,

  toString() {
    return `{name: "${this.name}", age: ${this.age}}`;
  }
};

alert(user); // {name: "John", age: 30}

…Nhưng trong quá trình phát triển, các thuộc tính mới được thêm vào, các thuộc tính cũ được đổi tên và loại bỏ. Cập nhật

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
1 như vậy mỗi lần có thể trở thành một nỗi đau. Chúng ta có thể thử lặp qua các thuộc tính trong đó, nhưng nếu đối tượng phức tạp và có các đối tượng lồng nhau trong các thuộc tính thì sao?

May mắn thay, không cần phải viết mã để xử lý tất cả những điều này. Nhiệm vụ đã được giải quyết rồi

JSON (Ký hiệu đối tượng JavaScript) là định dạng chung để biểu thị các giá trị và đối tượng. Nó được mô tả như trong tiêu chuẩn RFC 4627. Ban đầu, nó được tạo cho JavaScript, nhưng nhiều ngôn ngữ khác cũng có thư viện để xử lý nó. Vì vậy, thật dễ dàng để sử dụng JSON để trao đổi dữ liệu khi máy khách sử dụng JavaScript và máy chủ được viết trên Ruby/PHP/Java/Sao cũng được

JavaScript cung cấp các phương thức

  • // a number in JSON is just a number
    alert( JSON.stringify(1) ) // 1
    
    // a string in JSON is still a string, but double-quoted
    alert( JSON.stringify('test') ) // "test"
    
    alert( JSON.stringify(true) ); // true
    
    alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
    2 để chuyển đổi các đối tượng thành JSON
  • // a number in JSON is just a number
    alert( JSON.stringify(1) ) // 1
    
    // a string in JSON is still a string, but double-quoted
    alert( JSON.stringify('test') ) // "test"
    
    alert( JSON.stringify(true) ); // true
    
    alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
    3 để chuyển đổi JSON trở lại thành một đối tượng

Chẳng hạn, ở đây chúng tôi

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2 một sinh viên

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/

Phương thức

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
5 lấy đối tượng và chuyển đổi nó thành một chuỗi

Chuỗi

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
6 kết quả được gọi là đối tượng được mã hóa hoặc tuần tự hóa hoặc sắp xếp theo thứ tự JSON. Chúng tôi đã sẵn sàng để gửi nó qua dây hoặc đưa vào kho lưu trữ dữ liệu đơn giản

Xin lưu ý rằng một đối tượng được mã hóa JSON có một số điểm khác biệt quan trọng so với đối tượng theo nghĩa đen

  • Chuỗi sử dụng dấu ngoặc kép. Không có dấu ngoặc đơn hoặc backticks trong JSON. Vì vậy,
    // a number in JSON is just a number
    alert( JSON.stringify(1) ) // 1
    
    // a string in JSON is still a string, but double-quoted
    alert( JSON.stringify('test') ) // "test"
    
    alert( JSON.stringify(true) ); // true
    
    alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
    7 trở thành
    // a number in JSON is just a number
    alert( JSON.stringify(1) ) // 1
    
    // a string in JSON is still a string, but double-quoted
    alert( JSON.stringify('test') ) // "test"
    
    alert( JSON.stringify(true) ); // true
    
    alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
    8
  • Tên thuộc tính đối tượng cũng được trích dẫn kép. Đó là bắt buộc. Vì vậy,
    // a number in JSON is just a number
    alert( JSON.stringify(1) ) // 1
    
    // a string in JSON is still a string, but double-quoted
    alert( JSON.stringify('test') ) // "test"
    
    alert( JSON.stringify(true) ); // true
    
    alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
    9 trở thành
    let user = {
      sayHi() { // ignored
        alert("Hello");
      },
      [Symbol("id")]: 123, // ignored
      something: undefined // ignored
    };
    
    alert( JSON.stringify(user) ); // {} (empty object)
    0

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2 cũng có thể được áp dụng cho người nguyên thủy

JSON hỗ trợ các kiểu dữ liệu sau

  • Đối tượng
    let user = {
      sayHi() { // ignored
        alert("Hello");
      },
      [Symbol("id")]: 123, // ignored
      something: undefined // ignored
    };
    
    alert( JSON.stringify(user) ); // {} (empty object)
    2
  • Mảng
    let user = {
      sayHi() { // ignored
        alert("Hello");
      },
      [Symbol("id")]: 123, // ignored
      something: undefined // ignored
    };
    
    alert( JSON.stringify(user) ); // {} (empty object)
    3
  • nguyên thủy
    • dây,
    • con số,
    • giá trị boolean
      let user = {
        sayHi() { // ignored
          alert("Hello");
        },
        [Symbol("id")]: 123, // ignored
        something: undefined // ignored
      };
      
      alert( JSON.stringify(user) ); // {} (empty object)
      4,
    • let user = {
        sayHi() { // ignored
          alert("Hello");
        },
        [Symbol("id")]: 123, // ignored
        something: undefined // ignored
      };
      
      alert( JSON.stringify(user) ); // {} (empty object)
      5

Ví dụ

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]

JSON là đặc tả ngôn ngữ độc lập với dữ liệu, do đó, một số thuộc tính đối tượng dành riêng cho JavaScript bị bỏ qua bởi

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2

cụ thể là

  • Thuộc tính hàm (phương thức)
  • Các khóa và giá trị tượng trưng
  • Thuộc tính lưu trữ
    let user = {
      sayHi() { // ignored
        alert("Hello");
      },
      [Symbol("id")]: 123, // ignored
      something: undefined // ignored
    };
    
    alert( JSON.stringify(user) ); // {} (empty object)
    7

let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)

Thường thì tốt thôi. Nếu đó không phải là điều chúng tôi muốn, thì chúng tôi sẽ sớm xem cách tùy chỉnh quy trình

Điều tuyệt vời là các đối tượng lồng nhau được hỗ trợ và chuyển đổi tự động

Ví dụ

let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/

Hạn chế quan trọng. không được có tham chiếu vòng tròn

Ví dụ

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON

Ở đây, việc chuyển đổi không thành công, vì tham chiếu vòng tròn.

let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
8 tài liệu tham khảo
let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
9, và
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
0 tài liệu tham khảo
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
1

Cú pháp đầy đủ của

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2 là

let json = JSON.stringify(value[, replacer, space])

valueMột giá trị để mã hóa. replacerMảng thuộc tính để mã hóa hoặc hàm ánh xạ
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
3. không gianSố lượng không gian để sử dụng để định dạng

Hầu hết thời gian,

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2 chỉ được sử dụng với đối số đầu tiên. Nhưng nếu chúng ta cần tinh chỉnh quy trình thay thế, chẳng hạn như lọc ra các tham chiếu vòng, chúng ta có thể sử dụng đối số thứ hai của
// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2

Nếu chúng ta chuyển một mảng thuộc tính cho nó, thì chỉ những thuộc tính này sẽ được mã hóa

Ví dụ

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}

Ở đây có lẽ chúng ta quá khắt khe. Danh sách thuộc tính được áp dụng cho toàn bộ cấu trúc đối tượng. Vì vậy, các đối tượng trong

let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
6 trống, vì
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
7 không có trong danh sách

Hãy đưa vào danh sách mọi thuộc tính ngoại trừ

let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
8 sẽ gây ra tham chiếu vòng

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
/*
{
  "title":"Conference",
  "participants":[{"name":"John"},{"name":"Alice"}],
  "place":{"number":23}
}
*/

Bây giờ mọi thứ ngoại trừ

let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
9 đều được đăng nhiều kỳ. Nhưng danh sách tài sản khá dài

May mắn thay, chúng ta có thể sử dụng một hàm thay vì một mảng như

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
0

Hàm sẽ được gọi cho mỗi cặp

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
1 và sẽ trả về giá trị “đã thay thế”, giá trị này sẽ được sử dụng thay cho giá trị ban đầu. Hoặc
let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
7 nếu giá trị bị bỏ qua

Trong trường hợp của chúng tôi, chúng tôi có thể trả lại

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
3 “nguyên trạng” cho mọi thứ ngoại trừ
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
9. Để bỏ qua
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
9, mã bên dưới trả về
let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
7

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, function replacer(key, value) {
  alert(`${key}: ${value}`);
  return (key == 'occupiedBy') ? undefined : value;
}));

/* key:value pairs that come to replacer:
:             [object Object]
title:        Conference
participants: [object Object],[object Object]
0:            [object Object]
name:         John
1:            [object Object]
name:         Alice
place:        [object Object]
number:       23
occupiedBy: [object Object]
*/

Xin lưu ý rằng hàm

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
0 nhận mọi cặp khóa/giá trị bao gồm các đối tượng lồng nhau và các mục mảng. Nó được áp dụng đệ quy. Giá trị của
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
8 bên trong
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
0 là đối tượng chứa thuộc tính hiện tại

Cuộc gọi đầu tiên là đặc biệt. Nó được tạo bằng cách sử dụng một “đối tượng bao bọc” đặc biệt.

let json = JSON.stringify(value[, replacer, space])
0. Nói cách khác, cặp
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
1 đầu tiên có một khóa trống và giá trị là toàn bộ đối tượng mục tiêu. Đó là lý do tại sao dòng đầu tiên là
let json = JSON.stringify(value[, replacer, space])
2 trong ví dụ trên

Ý tưởng là cung cấp càng nhiều năng lượng cho

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
0 càng tốt. nó có cơ hội phân tích và thay thế/bỏ qua toàn bộ đối tượng nếu cần

Đối số thứ ba của

let json = JSON.stringify(value[, replacer, space])
4 là số lượng khoảng trống để sử dụng cho định dạng đẹp

Trước đây, tất cả các đối tượng được xâu chuỗi đều không có khoảng cách thụt vào và khoảng trắng thừa. Điều đó tốt nếu chúng ta muốn gửi một đối tượng qua mạng. Đối số

let json = JSON.stringify(value[, replacer, space])
5 được sử dụng riêng cho một đầu ra đẹp

Đây

let json = JSON.stringify(value[, replacer, space])
6 yêu cầu JavaScript hiển thị các đối tượng lồng nhau trên nhiều dòng, với thụt lề 2 khoảng trắng bên trong một đối tượng

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
0

Đối số thứ ba cũng có thể là một chuỗi. Trong trường hợp này, chuỗi được sử dụng để thụt đầu dòng thay vì một số khoảng trắng

Tham số

let json = JSON.stringify(value[, replacer, space])
5 chỉ được sử dụng cho mục đích ghi nhật ký và đầu ra đẹp

Giống như

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
1 để chuyển đổi chuỗi, một đối tượng có thể cung cấp phương thức
let json = JSON.stringify(value[, replacer, space])
9 để chuyển đổi sang JSON.
// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
2 tự động gọi nó nếu có

Ví dụ

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
1

Ở đây chúng ta có thể thấy rằng

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
1
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
2 đã trở thành một chuỗi. Đó là bởi vì tất cả các ngày đều có phương thức
let json = JSON.stringify(value[, replacer, space])
9 tích hợp trả về loại chuỗi như vậy

Bây giờ, hãy thêm một

let json = JSON.stringify(value[, replacer, space])
9 tùy chỉnh cho đối tượng của chúng ta
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
1
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
6

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
2

Như chúng ta có thể thấy,

let json = JSON.stringify(value[, replacer, space])
9 được sử dụng cho cả cuộc gọi trực tiếp
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
8 và khi
let meetup = {
  title: "Conference",
  room: {
    number: 23,
    participants: ["john", "ann"]
  }
};

alert( JSON.stringify(meetup) );
/* The whole structure is stringified:
{
  "title":"Conference",
  "room":{"number":23,"participants":["john","ann"]},
}
*/
1 được lồng trong một đối tượng được mã hóa khác

Để giải mã một chuỗi JSON, chúng ta cần một phương thức khác có tên JSON. phân tích cú pháp

cú pháp

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
3

chuỗi strJSON để phân tích cú pháp. hồi sinh Hàm tùy chọn (khóa, giá trị) sẽ được gọi cho mỗi cặp
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: ["john", "ann"]
};

meetup.place = room;       // meetup references room
room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
1 và có thể biến đổi giá trị

Ví dụ

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
4

Hoặc cho các đối tượng lồng nhau

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
5

JSON có thể phức tạp đến mức cần thiết, các đối tượng và mảng có thể bao gồm các đối tượng và mảng khác. Nhưng chúng phải tuân theo cùng một định dạng JSON

Dưới đây là những lỗi điển hình trong JSON viết tay (đôi khi chúng ta phải viết nó cho mục đích gỡ lỗi)

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
6

Ngoài ra, JSON không hỗ trợ bình luận. Thêm một nhận xét vào JSON làm cho nó không hợp lệ

Có một định dạng khác có tên JSON5, cho phép các khóa, nhận xét không được trích dẫn, v.v. Nhưng đây là một thư viện độc lập, không có trong đặc điểm kỹ thuật của ngôn ngữ

JSON thông thường nghiêm ngặt như vậy không phải vì các nhà phát triển của nó lười biếng, mà để cho phép triển khai thuật toán phân tích cú pháp dễ dàng, đáng tin cậy và rất nhanh

Hãy tưởng tượng, chúng ta có một đối tượng

let user = {
  sayHi() { // ignored
    alert("Hello");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
9 được xâu chuỗi từ máy chủ

Nó trông như thế này

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
7

…Và bây giờ chúng ta cần deserialize nó, để quay lại thành đối tượng JavaScript

Hãy làm điều đó bằng cách gọi

// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
3

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  spouse: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "spouse": null
}
*/
8

Rất tiếc. Một lỗi

Giá trị của

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
/*
{
  "title":"Conference",
  "participants":[{"name":"John"},{"name":"Alice"}],
  "place":{"number":23}
}
*/
3 là một chuỗi, không phải đối tượng
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
/*
{
  "title":"Conference",
  "participants":[{"name":"John"},{"name":"Alice"}],
  "place":{"number":23}
}
*/
4. Làm thế nào mà
// a number in JSON is just a number
alert( JSON.stringify(1) ) // 1

// a string in JSON is still a string, but double-quoted
alert( JSON.stringify('test') ) // "test"

alert( JSON.stringify(true) ); // true

alert( JSON.stringify([1, 2, 3]) ); // [1,2,3]
3 biết rằng nó sẽ chuyển đổi chuỗi đó thành một chuỗi
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
/*
{
  "title":"Conference",
  "participants":[{"name":"John"},{"name":"Alice"}],
  "place":{"number":23}
}
*/
4?

Hãy chuyển sang ____1_______3 hàm hồi sinh làm đối số thứ hai, hàm này trả về tất cả các giá trị “nguyên trạng”, nhưng

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
1 sẽ trở thành một ____36_______4

Làm cách nào để chuyển hàm JavaScript trong JSON?

dữ liệu = '[{"a". 1,"b". 2,"c". 3},{"a". 4,"b". 5,"c". 6},{"a". 7,"b". 8,"c". 9}]'; . use JSON. hàm phân tích cú pháp để phân tích dữ liệu chuỗi thành đối tượng javascript rồi truyền đối tượng .

Chúng ta có thể gọi hàm trong tệp JSON không?

Đó là đối tượng JavaScript, không phải đối tượng JSON. Để gọi hàm, hãy sử dụng Bootstrapper .

Bạn có thể sử dụng JavaScript trong JSON không?

Như chúng tôi đã đề cập trước đây, JSON hoạt động với bất kỳ ngôn ngữ lập trình nào. Tuy nhiên, bạn chỉ có thể làm việc với các đối tượng JavaScript bằng JavaScript . Cú pháp trong JSON và JavaScript tương tự nhau. Sự khác biệt là các đối tượng JavaScript xuất hiện trong chuỗi thay vì dấu ngoặc kép.

Làm cách nào để gọi một hàm JavaScript?

Có một vài cách khác nhau để gọi một hàm trong JavaScript. Cách phổ biến nhất đơn giản là sử dụng tên hàm theo sau là dấu ngoặc đơn . Nếu bạn có một hàm được lưu trữ trong một biến, bạn có thể gọi nó bằng cách sử dụng tên biến theo sau dấu ngoặc đơn.