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

Duyệt mảng JSON trong JavaScript

Để duyệt mảng JSON, sử dụng JSON.parse() để chuyển chuỗi thành đối tượng.

Ví dụ

Mã nguồn:

var apiValues =    [       '{"name": "John", "scores": [78, 89]}',       '{"name": "David", "scores": [58, 98]}',       '{"name": "Bob", "scores": [56, 79]}',       '{"name": "Mike", "scores": [94, 91]}'    ]; var parseJSONObject = apiValues.map(obj => JSON.parse(obj)); console.log("The original String : ", apiValues); console.log("The JSON Objects : ", parseJSONObject);

Chạy với lệnh:

node fileName.js

Tên file: demo252.js.

Kết quả

PS C:\Users\Amit\javascript-code> node demo252.js The original String :  [    '{"name": "John", "scores": [78, 89]}',   '{"name": "David", "scores": [58, 98]}',   '{"name": "Bob", "scores": [56, 79]}',   '{"name": "Mike", "scores": [94, 91]}' ] The JSON Objects :  [   { name: 'John', scores: [ 78, 89 ] },   { name: 'David', scores: [ 58, 98 ] },   { name: 'Bob', scores: [ 56, 79 ] },   { name: 'Mike', scores: [ 94, 91 ] } ]