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

วิธี Parse JSON Object ใน JavaScript

ใช้ JSON.parse() แปลงสตริง JSON เป็น JavaScript Object และ JSON.stringify() ทำทางกลับ

ตัวอย่างจากบทความ

<!DOCTYPE html>
<html>
  <body>
    <script>
      myData = JSON.parse('{"event1":{"title":"Employment period","start":"12/29/2011 10:20 ","end":"12/15/2013 00:00 "},"event2":{"title":"Employment period","start":"12/14/2011 10:20 ","end":"12/18/2013 00:00 "}}');
      myArray = [];
      for(var e in myData){
        var dataCopy = myData[e];
        for(key in dataCopy){
          if(key == "start" || key == "end"){
            dataCopy[key] = new Date(dataCopy[key]);
          }
        }
        myArray.push(dataCopy);
      }
      document.write(JSON.stringify(myArray));
    </script>
  </body>
</html>

พื้นฐาน JSON.parse() และ JSON.stringify()

// String → Object
const jsonStr = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // "John"

// Object → String
const obj2 = { name: "Jane", age: 25 };
const str = JSON.stringify(obj2);
console.log(str); // '{"name":"Jane","age":25}'

// Pretty print
JSON.stringify(obj2, null, 2);
/*
{
  "name": "Jane",
  "age": 25
}
*/

Reviver Function (Parameter ที่ 2 ของ parse)

const json = '{"date": "2024-01-15T10:30:00.000Z", "value": 100}';

const obj = JSON.parse(json, (key, value) => {
  if (key === 'date') {
    return new Date(value); // แปลง string เป็น Date object
  }
  return value;
});

console.log(obj.date instanceof Date); // true
console.log(obj.date.getFullYear());   // 2024

Replacer Function (Parameter ที่ 2 ของ stringify)

const obj = {
  name: "John",
  password: "secret",
  createdAt: new Date()
};

const str = JSON.stringify(obj, (key, value) => {
  if (key === 'password') return undefined; // ไม่รวม password
  if (value instanceof Date) return value.toISOString(); // แปลง Date
  return value;
});

console.log(str); // '{"name":"John","createdAt":"2024-01-15T10:30:00.000Z"}'

Error Handling

function safeParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (e) {
    console.error('Invalid JSON:', e.message);
    return null;
  }
}

safeParse('{"valid": true}');    // {valid: true}
safeParse('{invalid json}');     // null + log error

ข้อจำกัดของ JSON

ไม่รองรับทางเลือก
Functionเก็บเป็น string หรือใช้ custom serializer
undefinedถูกละเว้น (omit)
Symbolถูกละเว้น
Circular ReferenceError - ใช้ flatted library
Dateแปลงเป็น ISO string อัตโนมัติ
RegExp, Error, Map, Setกลายเป็น {}

ใช้กับ API Response

async function fetchUsers() {
  const response = await fetch('/api/users');
  const text = await response.text(); // ได้ raw text
  
  try {
    const users = JSON.parse(text);
    return users;
  } catch (e) {
    throw new Error('Invalid JSON response');
  }
}

// หรือใช้ response.json() โดยตรง (แนะนำ)
async function fetchUsers() {
  const response = await fetch('/api/users');
  if (!response.ok) throw new Error('HTTP ' + response.status);
  return response.json(); // parse อัตโนมัติ
}