Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แปลงค่าสตริงเป็นอาร์เรย์ใน JavaScript ด้วย JSON.parse()

การแปลงสตริง JSON เป็นอาร์เรย์ของออบเจกต์

เมื่อมีข้อมูลในรูปแบบสตริง JSON ที่ต้องการแปลงเป็นอาร์เรย์ของออบเจกต์ ให้ใช้เมธอด JSON.parse()

ตัวอย่างโค้ด

var customerDetails = '[{"name": "John", "countryName": "US"}, {"name": "David", "countryName": "AUS"}, {"name": "Bob", "countryName": "UK"}]';

console.log("ค่าเดิม = " + customerDetails);

// แปลงสตริงเป็นอาร์เรย์
var convertStringToArray = JSON.parse(customerDetails);

console.log("หลังแปลงสตริงเป็นอาร์เรย์ออบเจกต์ = ");
console.log(convertStringToArray);

วิธีรันโปรแกรม

บันทึกเป็น fileName.js และรันด้วย:

node fileName.js

ผลลัพธ์

The actual value=[{"name": "John", "countryName": "US"}, {"name": "David", "countryName": "AUS"}, {"name": "Bob", "countryName": "UK"}]
After converting string to array objects=[
  { name: 'John', countryName: 'US' },
  { name: 'David', countryName: 'AUS' },
  { name: 'Bob', countryName: 'UK' }
]

คำอธิบาย

  • JSON.parse() แปลงสตริง JSON ที่ถูกต้องให้กลายเป็นออบเจกต์หรืออาร์เรย์ของ JavaScript
  • สตริงต้องอยู่ในรูปแบบ JSON ที่ถูกต้อง (ใช้ double quotes รอบ key และ string value)
  • หากสตริงไม่ถูกต้อง จะเกิดข้อผิดพลาด SyntaxError