0Pricing
React Native Academy · บทเรียน

การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON

แปลงออบเจ็กต์ JavaScript เป็น JSON ก่อนเขียนลง AsyncStorage และแปลงกลับเมื่ออ่าน โดยจัดการค่า null สำหรับการเปิดแอปครั้งแรก

การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why AsyncStorage Only Stores Strings

AsyncStorage is a string-only key-value store — you cannot store JavaScript objects, arrays, numbers, or booleans directly. To save any non-string value you must convert it to a string first, and convert it back when reading. The standard approach is JSON.stringify before writing and JSON.parse after reading.

Saving an Object with JSON.stringify

Call JSON.stringify on your JavaScript object before passing it to setItem. This converts the object to a JSON string that AsyncStorage can store. If the object contains functions, undefined, or circular references, JSON.stringify will omit or error on those values — keep stored objects plain and serializable.

const userProfile = {
  name: 'Alice',
  email: 'alice@example.com',
  preferences: { theme: 'dark', language: 'en' },
};

async function saveProfile(profile: object) {
  try {
    await AsyncStorage.setItem('userProfile', JSON.stringify(profile));
  } catch (err) {
    console.error('Failed to save profile:', err);
  }
}

Reading and Parsing with JSON.parse

When reading back a stored JSON string, call JSON.parse on the returned value to convert it back into a JavaScript object. Always wrap this in a try-catch because JSON.parse throws a SyntaxError if the stored value is not valid JSON — for example, if it was corrupted or written by a different code path.

async function loadProfile() {
  try {
    const json = await AsyncStorage.getItem('userProfile');
    if (json === null) return null; // never saved before
    return JSON.parse(json);
  } catch (err) {
    console.error('Failed to load or parse profile:', err);
    return null;
  }
}

Handling null on First Launch

A user who has never opened the app will have nothing in AsyncStorage. getItem returns null before any setItem call has been made. Always check for null before parsing and return an appropriate default value — typically the initial state used when the app launches for the very first time.

const DEFAULT_SETTINGS = { theme: 'light', language: 'en', notifications: true };

async function loadSettings() {
  const json = await AsyncStorage.getItem('settings');
  if (json === null) return DEFAULT_SETTINGS; // first launch
  try {
    return JSON.parse(json);
  } catch {
    return DEFAULT_SETTINGS; // corrupted data — fall back to defaults
  }
}

Storing Arrays

Arrays are also not directly supported by AsyncStorage but serialize perfectly with JSON.stringify. Use this pattern to persist lists such as recent searches, bookmarked items, or favorite IDs. After parsing the JSON string back, the result is a proper JavaScript array that you can spread, map, and filter normally.

// Save an array
const favorites = ['post_1', 'post_3', 'post_7'];
await AsyncStorage.setItem('favorites', JSON.stringify(favorites));

// Load the array
const json = await AsyncStorage.getItem('favorites');
const favorites = json ? JSON.parse(json) as string[] : [];
console.log(favorites); // ['post_1', 'post_3', 'post_7']

Merging New Data into an Existing Object

When updating only one field of a stored object, read the full object first, merge in the new value using spread, then write it back. This avoids accidentally overwriting other fields. For performance in write-heavy scenarios, consider batching updates and debouncing writes so you are not writing to disk on every keystroke.

async function updateTheme(newTheme: string) {
  const json = await AsyncStorage.getItem('settings');
  const current = json ? JSON.parse(json) : DEFAULT_SETTINGS;
  const updated = { ...current, theme: newTheme };
  await AsyncStorage.setItem('settings', JSON.stringify(updated));
}

Type-Safe Storage Helpers

Create typed wrapper functions for each stored object to avoid scattering JSON.stringify and JSON.parse throughout the codebase. Each helper encapsulates the key name, the serialization, and the default value. TypeScript generics make it easy to create a single reusable helper for any type.

async function saveObject<T>(key: string, value: T): Promise<void> {
  await AsyncStorage.setItem(key, JSON.stringify(value));
}

async function loadObject<T>(key: string, defaultValue: T): Promise<T> {
  const json = await AsyncStorage.getItem(key);
  if (json === null) return defaultValue;
  try {
    return JSON.parse(json) as T;
  } catch {
    return defaultValue;
  }
}

// Usage:
const profile = await loadObject<UserProfile>('profile', defaultProfile);

Storing Primitive Numbers and Booleans

Numbers and booleans must also be converted to strings when stored in AsyncStorage. JSON.stringify(42) gives '42' and JSON.parse('42') gives 42 back. For simple values you can also use String(value) to write and then Number(value) or compare to 'true' to read, but JSON.stringify/parse is more consistent across all types.

// Store a boolean
await AsyncStorage.setItem('onboardingComplete', JSON.stringify(true));

// Read it back
const raw = await AsyncStorage.getItem('onboardingComplete');
const complete = raw !== null ? JSON.parse(raw) as boolean : false;

// Store a number
await AsyncStorage.setItem('highScore', JSON.stringify(2048));
const score = JSON.parse(await AsyncStorage.getItem('highScore') ?? '0') as number;

Dates and Timestamps

JavaScript Date objects are not directly JSON-serializable — JSON.stringify(new Date()) produces an ISO string, but JSON.parse gives you back a string, not a Date. Store dates as ISO strings or Unix timestamps (numbers) and explicitly convert them back to Date objects after parsing.

// Store date as ISO string
await AsyncStorage.setItem('lastLogin', new Date().toISOString());

// Read and convert back to Date
const raw = await AsyncStorage.getItem('lastLogin');
const lastLogin = raw ? new Date(raw) : null;
console.log(lastLogin?.toLocaleDateString());

Validating Stored Data Shape

Stored data can become outdated as your app evolves. After parsing JSON from AsyncStorage, validate the returned object shape before using it. Check for required fields and fall back to defaults if they are missing. This prevents crashes when an old app version stored data with fewer fields than the current version expects.

function isValidProfile(obj: any): obj is UserProfile {
  return (
    typeof obj === 'object' &&
    obj !== null &&
    typeof obj.name === 'string' &&
    typeof obj.email === 'string'
  );
}

const parsed = json ? JSON.parse(json) : null;
const profile = isValidProfile(parsed) ? parsed : DEFAULT_PROFILE;

Performance: Avoid Frequent Reads

Reading from AsyncStorage on every render or in a tight loop is slow because it involves asynchronous I/O. Load data once on app startup (or screen mount), store it in component state or a global store (like Zustand), and read from state for the rest of the session. Write to AsyncStorage only when values actually change, not on every re-render.

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: JSON.stringify before writing and JSON.parse after reading are the standard pattern for storing objects in AsyncStorage, checking for null prevents crashes on first launch before any data has been saved, and type-safe wrapper functions encapsulate serialization to keep your codebase clean. Next up we explore building a persistent settings screen.

คำถามที่พบบ่อย

บทเรียน “การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON”

แปลงออบเจ็กต์ JavaScript เป็น JSON ก่อนเขียนลง AsyncStorage และแปลงกลับเมื่ออ่าน โดยจัดการค่า null สำหรับการเปิดแอปครั้งแรก คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การอ่านและเขียนด้วย AsyncStorage
  2. การจัดเก็บและแยกวิเคราะห์ออบเจ็กต์ JSON
  3. การสร้างหน้าจอการตั้งค่าถาวร
  4. การล้างพื้นที่จัดเก็บและกลยุทธ์การย้ายข้อมูล
← กลับไปที่ React Native Academy