๐ŸŒ Web Development

JSON

JavaScript Object Notation

JSON is a lightweight data interchange format that is easy for humans to read and write. Composed of key-value pairs, it is the standard data format for REST APIs, and although it originated from JavaScript, it is language-independent.

๐Ÿ“– Detailed Explanation

JSON (JavaScript Object Notation) is a text-based, lightweight data interchange format first specified by Douglas Crockford in 2001. It was inspired by JavaScript's object literal syntax, but it is language-independent, so it is natively supported by almost all programming languages, including Python, Java, C#, and Go.

JSON consists of two structures. The first is a collection of name/value pairs (an object), and the second is an ordered list of values (an array). The supported data types are limited to strings, numbers, booleans, null, objects, and arrays, which makes it both simple and powerful. A notable characteristic is that it does not support comments.

The reasons JSON came to replace XML are clear. Compared to XML, it is faster to parse, its data size is smaller, and it is easier to read. When representing the same data, JSON needs no more than half the size of XML. As a result, it has become established as the standard format in REST APIs, configuration files (package.json, tsconfig.json), and NoSQL databases (MongoDB, CouchDB).

In practice, JSON is the standard format for HTTP API communication. It is widely used for data exchange between frontend and backend, microservice communication between servers, storing configuration files, and structuring log data. Extended formats such as JSON5 and JSONC allow comments and trailing commas, so they are used for configuration files, and JSON Schema is used to validate JSON data.

๐Ÿ’ป Code Example

// JSON ๊ธฐ๋ณธ ๊ตฌ์กฐ์™€ JavaScript์—์„œ์˜ ํ™œ์šฉ

// 1. JSON ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ
const userJson = `{
  "id": 1,
  "name": "ํ™๊ธธ๋™",
  "email": "hong@example.com",
  "isActive": true,
  "age": 28,
  "roles": ["admin", "editor"],
  "profile": {
    "avatar": "https://example.com/avatar.png",
    "bio": "์†Œํ”„ํŠธ์›จ์–ด ๊ฐœ๋ฐœ์ž"
  },
  "lastLogin": null
}`;

// 2. JSON ํŒŒ์‹ฑ (๋ฌธ์ž์—ด โ†’ ๊ฐ์ฒด)
const user = JSON.parse(userJson);
console.log(user.name);           // "ํ™๊ธธ๋™"
console.log(user.roles[0]);       // "admin"
console.log(user.profile.bio);    // "์†Œํ”„ํŠธ์›จ์–ด ๊ฐœ๋ฐœ์ž"

// 3. JSON ์ง๋ ฌํ™” (๊ฐ์ฒด โ†’ ๋ฌธ์ž์—ด)
const newUser = {
  id: 2,
  name: "๊น€์ฒ ์ˆ˜",
  email: "kim@example.com",
  createdAt: new Date()  // Date๋Š” ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜๋จ
};

// ๊ธฐ๋ณธ ์ง๋ ฌํ™”
const jsonString = JSON.stringify(newUser);
console.log(jsonString);
// {"id":2,"name":"๊น€์ฒ ์ˆ˜","email":"kim@example.com","createdAt":"2024-01-15T..."}

// ๊ฐ€๋…์„ฑ ์žˆ๋Š” ํฌ๋งทํŒ… (๋“ค์—ฌ์“ฐ๊ธฐ 2์นธ)
const prettyJson = JSON.stringify(newUser, null, 2);
console.log(prettyJson);

// 4. replacer๋กœ ํŠน์ • ํ•„๋“œ๋งŒ ํฌํ•จ
const publicData = JSON.stringify(user, ['id', 'name', 'email'], 2);

// 5. reviver๋กœ ํŒŒ์‹ฑ ์‹œ ๋ฐ์ดํ„ฐ ๋ณ€ํ™˜
const jsonWithDate = '{"name": "์ด๋ฒคํŠธ", "date": "2024-01-15T10:00:00Z"}';
const event = JSON.parse(jsonWithDate, (key, value) => {
  if (key === 'date') return new Date(value);
  return value;
});
console.log(event.date instanceof Date);  // true

// 6. API ์‘๋‹ต์—์„œ JSON ์ฒ˜๋ฆฌ (์‹ค๋ฌด ํŒจํ„ด)
async function fetchUser(userId: number) {
  try {
    const response = await fetch(`/api/users/${userId}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();  // ์ž๋™์œผ๋กœ JSON.parse ์ˆ˜ํ–‰
    return data;
  } catch (error) {
    console.error('JSON ํŒŒ์‹ฑ ์˜ค๋ฅ˜:', error);
    throw error;
  }
}

// 7. ๊นŠ์€ ๋ณต์‚ฌ์— JSON ํ™œ์šฉ (์ฃผ์˜: ํ•จ์ˆ˜, undefined, Symbol ์†์‹ค)
const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 3;
console.log(original.b.c);  // 2 (์›๋ณธ ์œ ์ง€)

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

๐Ÿ’ฌ Situation: A team discussion about the API response format

Backend "We're designing a new API response, so please give your opinion on the JSON structure. We want to keep error responses in a consistent format as well."
Frontend "It would be nice if both success and error responses used a wrapper shape like { success: boolean, data: T, error?: { code: string, message: string } }. It makes type guard handling easier on the frontend."
Backend "Sounds good. And how about standardizing dates on the ISO 8601 format (2024-01-15T10:00:00Z) and sending numbers like monetary amounts as strings because of precision issues?"
Frontend "I agree. In JavaScript, large integers lose precision once they exceed Number.MAX_SAFE_INTEGER. And if we document the response structure with JSON Schema, it seems the frontend could also do runtime validation with Zod or io-ts."

โš ๏ธ Cautions

๐Ÿ”— Related Terms

๐Ÿ“š Learn More