Skip to content

JSON 치트시트

데이터 교환을 위한 경량 데이터 교환 형식입니다.

01

시작하기

기본 구조

JSON은 6개 데이터 타입을 지원합니다: string, number, boolean, null, array, object. 키는 큰따옴표가 붙은 문자열이어야 합니다. JSON은 언어 독립적이며 사람과 기계가 모두 읽기 쉽습니다.

json
{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "height": 1.65,
  "nullValue": null,
  "hobbies": ["reading", "coding", "music"],
  "address": {
    "city": "NYC",
    "zip": "10001"
  }
}

JSON 문법 규칙

JSON은 엄격한 문법을 갖습니다: 키와 문자열은 큰따옴표만, 쉼표가 요소를 구분하며, 끝 쉼표는 금지입니다. 전체 문서는 단일 JSON 값이어야 합니다. 표준 JSON에는 주석이 없으니 — 필요하면 전처리기나 JSON5를 쓰세요.

json
{
  "key": "value",          // key MUST be a double-quoted string
  "nested": { "a": 1 },    // objects use { } with comma-separated pairs
  "list": [1, 2, 3]        // arrays use [ ] with comma-separated values
}

// Rules:
// - Double quotes only for strings and keys (no single quotes)
// - Comma separates members; NO trailing comma
// - The whole document is ONE value (usually an object or array)
// - No comments allowed in standard JSON

JSON의 주석

표준 JSON은 주석을 금지합니다. 흔한 우회법: 코드가 무시하는 '_comment' 필드 추가, JSONC/JSON5 사용(VS Code와 많은 도구가 지원), 또는 comment-json이나 JSON.minify 같은 라이브러리로 파싱 전 주석 제거.

json
// Standard JSON does NOT allow comments.

// Workaround 1: include a descriptive field
{
  "_comment": "This is a config file for the app",
  "port": 8080
}

// Workaround 2: use JSON5 or JSONC (VS Code settings)
{
  // line comment
  "port": 8080 /* block comment */
}

// Workaround 3: strip comments before parsing
// (e.g., JSON.minify, comment-json npm package)

공백 & 포매팅

문자열 밖의 공백은 무의미합니다 — 컴팩트 형식과 예쁜 형식이 같은 값으로 파싱됩니다. 컴팩트 JSON은 대역폭을 아끼고, 예쁘게 인쇄된 형식(2칸 들여쓰기가 흔함)은 가독성과 diff에 도움됩니다. 대부분의 직렬화기가 'pretty' 옵션을 제공합니다.

json
// These are all equivalent:

{"a":1,"b":2}                       // compact (no whitespace)

{ "a": 1, "b": 2 }                  // readable

{
  "a": 1,
  "b": 2
}                                   // pretty-printed

// Whitespace between tokens is insignificant.
// Use compact for transmission, pretty for humans.

파일 확장자 & MIME 타입

표준 파일 확장자는 .json이고 MIME 타입은 application/json입니다. JSONC, JSON5, GeoJSON, NDJSON 같은 변형은 각자의 관례를 갖습니다. 항상 UTF-8 인코딩을 쓰세요; BOM은 권장되지 않습니다.

json
// File extensions:
//   .json    standard JSON
//   .jsonc   JSON with comments (VS Code, TypeScript config)
//   .json5   JSON5 (relaxed syntax)
//   .geojson GeoJSON (geographic data)
//   .ndjson  Newline-Delimited JSON (JSON Lines)
//   .har     HTTP Archive (JSON-based)

// MIME type:
Content-Type: application/json

// Older/alternate MIME types (avoid):
//   text/json          (non-standard)
//   application/x-json (non-standard)

// UTF-8 is the default and recommended encoding.

JSON 값 분류

JSON 값은 여섯 타입으로 나뉩니다: string, number, boolean, null, array, object. 배열과 객체는 구조화되어 있습니다(다른 값을 담을 수 있음); 나머지는 프리미티브입니다. 유효한 JSON 문서는 하나의 값입니다 — 흔히 객체나 배열이지만 맨 숫자나 문자열도 유효합니다.

json
// A JSON value is exactly one of these six types:

"hello"                 // string
42                      // number
3.14                    // number
true                    // boolean
false                   // boolean
null                    // null
[1, 2, 3]               // array
{ "a": 1 }              // object

// Structured types: array, object
// Primitive types: string, number, boolean, null
// A standalone JSON document is a single value of any type.
02

데이터 타입

String 타입

JSON 문자열은 큰따옴표가 붙은 유니코드 텍스트입니다. 흔한 이스케이프: \"(따옴표), \\(백슬래시), \/(슬래시), \n, \t, \r, \b, \f, 그리고 임의의 유니코드 코드 포인트용 \uXXXX. 작은따옴표는 문자열 구분자로 허용되지 않습니다.

json
{
  "single": "double quotes only",
  "empty": "",
  "escaped": "He said \"hi\" and C:\\Users",
  "unicode": "Cafu00e9 \u00e9 \u1F600",
  "multiline": "line1\nline2\ttabbed"
}

// Strings MUST use double quotes.
// Single quotes are NOT valid in JSON.

Number 타입

JSON 숫자는 IEEE 754 배정밀도의 부분집합을 따릅니다: 정수, 소수, 과학적 표기(예: 6.022e23). 선행 0은 금지됩니다(007은 무효). NaN, Infinity, -Infinity는 유효하지 않습니다 — 필요하면 null이나 문자열로 인코딩하세요.

json
{
  "integer": 42,
  "negative": -7,
  "float": 3.14,
  "zero": 0,
  "scientific": 6.022e23,
  "small": 1.5e-10
}

// Numbers are NOT quoted.
// No leading zeros (007 is invalid).
// No NaN, Infinity, or -Infinity (not valid JSON).

Boolean 타입

JSON 불리언은 리터럴 키워드 true와 false입니다(소문자, 따옴표 없음). 따옴표가 붙은 'true'/'false'는 문자열입니다. JSON에는 0/1이나 yes/no를 불리언으로 다루는 개념이 없습니다 — 애플리케이션 코드에서 변환하세요.

json
{
  "enabled": true,
  "disabled": false,
  "flag": true
}

// Booleans are the bare keywords true and false.
// They are NOT quoted ("true" is a string).
// 0/1, yes/no, on/off are NOT booleans in JSON.

Null 타입

JSON null은 맨 키워드 null입니다(따옴표 없음). 값의 의도적 부재를 신호합니다. null은 빈 문자열 '', 0, false, 없는 키와 구별됩니다. 많은 언어가 null을 None/nil/null로 매핑합니다.

json
{
  "middleName": null,
  "deletedAt": null,
  "optional": null
}

// null is a bare keyword (unquoted).
// "null" (quoted) is a string, not null.
// null represents the intentional absence of value.

Array 타입

JSON 배열은 [ ]로 감싼 순서 있는 목록이며 쉼표로 구분되고 0 인덱스입니다. 혼합 타입과 중첩 배열/객체를 포함해 어떤 JSON 값이든 담을 수 있습니다. 빈 배열 []도 유효합니다. 순서는 보존되며 의미가 있습니다.

json
{
  "numbers": [1, 2, 3],
  "mixed": [1, "two", true, null],
  "nested": [[1, 2], [3, 4]],
  "objects": [
    { "id": 1 },
    { "id": 2 }
  ],
  "empty": []
}

// Arrays are ordered, zero-indexed, and can hold mixed types.

Object 타입

JSON 객체는 { }로 감싼 비순서 키/값 모음입니다. 키는 고유한 큰따옴표 문자열이어야 하고, 값은 어떤 JSON 타입이든 될 수 있습니다. 객체가 개념상 비순서지만 대부분의 파서가 삽입 순서를 유지합니다; 정확성을 위해 순서에 의존하지 마세요.

json
{
  "user": {
    "id": 1,
    "name": "Alice",
    "roles": ["admin", "user"],
    "active": true
  },
  "empty": {}
}

// Objects are unordered collections of key/value pairs.
// Keys MUST be unique strings (double-quoted).
// Values can be any JSON type.
03

문자열

문자열 기본

JSON 문자열은 큰따옴표가 붙은 유니코드 문자의 나열입니다. 슬래시는 이스케이프할 수 있지만(\/) 필요하지는 않습니다 — <script> 태그 안에 JSON을 넣을 때 유용합니다. 빈 문자열도 유효합니다.

json
{
  "name": "Alice",
  "email": "[email protected]",
  "url": "https://example.com/path?q=1",
  "path": "C:\\Users\\alice",
  "empty": ""
}

// Strings are double-quoted Unicode text.
// Forward slash may be escaped as \/ but does not have to be.

이스케이프 시퀀스

JSON이 지원하는 이스케이프: \"(따옴표), \\(백슬래시), \/(슬래시), \b(백스페이스), \f(폼피드), \n(개행), \r(캐리지 리턴), \t(탭), \uXXXX(유니코드 코드 포인트). 그 외의 백슬래시 시퀀스는 무효입니다.

json
{
  "quote": "She said \"hello\"",
  "backslash": "C:\\Users\\name",
  "newline": "line1\nline2",
  "tab": "col1\tcol2",
  "carriage": "a\rb",
  "backspace": "a\bb",
  "formfeed": "a\fb",
  "slash": "a\/b"
}

// Valid escapes: \" \\ \/ \b \f \n \r \t \uXXXX

유니코드 문자

임의의 유니코드 코드 포인트에는 \uXXXX를 쓰세요. U+FFFF 위의 문자(많은 이모지처럼)는 서러게이트 쌍이 필요합니다: \u 이스케이프 두 개. 현대 파서는 문자열에 raw UTF-8 문자를 직접 받기도 합니다 — \uXXXX는 주로 안전을 위해, 또는 문자를 입력할 수 없을 때 씁니다.

json
{
  "eacute": "Caf\u00e9",
  "euro": "Price: \u20ac10",
  "emoji": "Smile \ud83d\ude00",
  "chinese": "\u4f60\u597d",
  "raw": "Cafu00e9 u00e9 \u00e9"
}

// \uXXXX encodes a code point in the Basic Multilingual Plane.
// Surrogate pairs (two \u escapes) encode characters above U+FFFF.
// Modern parsers also accept the raw UTF-8 character directly.

문자열의 특수 문자

JSON 문자열 안에서는 큰따옴표와 백슬래시가 항상 이스케이프되어야 합니다(\"와 \\). 기타 특수 문자(HTML, SQL, 정규식)는 각자의 규칙을 따르지만, JSON은 \"와 \\(그리고 제어 문자)의 이스케이프만 요구합니다. 리터럴 백슬래시는 \\로 씁니다.

json
{
  "html": "<div class=\"x\">Hi</div>",
  "sql": "SELECT * FROM t WHERE name='O''Brien'",
  "regex": "^\\d{3}-\\d{4}$",
  "json": "{ \"k\": \"v\" }",
  "cmd": "echo \"hello\""
}

// Backslash is the universal escape character.
// To include a literal backslash, write \\.

여러 줄 문자열 (우회법)

JSON 문자열에는 리터럴 개행이 들어갈 수 없습니다 — \n으로 이스케이프해야 합니다. 여러 줄 콘텐츠에는 문자열에 \n을 넣거나, 줄 문자열의 배열을 쓰거나, 여러 줄 문자열을 지원하는 YAML이나 JSON5 같은 형식으로 전환하세요. 이스케이프되지 않은 리터럴 개행은 문법 오류입니다.

json
// JSON does NOT support real multi-line strings.
// The following is INVALID:
// { "text": "line1
// line2" }

// Workaround 1: escape the newline
{ "text": "line1\nline2" }

// Workaround 2: array of lines
{ "lines": ["line1", "line2"] }

// Workaround 3: JSON5 allows continued strings (still single logical line)

흔한 문자열 함정

흔한 문자열 오류: 작은따옴표 사용, 끝 쉼표 남기기, 안쪽 큰따옴표 이스케이프 잊기, \t/\n 이스케이프 대신 리터럴 제어 문자(탭/개행)를 넣는 것. 엄격한 파서는 이 모두를 거부합니다.

json
// WRONG: single quotes
// { 'name': 'Alice' }

// WRONG: trailing comma
// { "a": 1, }

// WRONG: unescaped quote
// { "msg": "He said "hi"" }

// WRONG: literal tab/newline in string
// { "x": "a<TAB>b" }

// RIGHT:
{ "name": "Alice", "msg": "He said \"hi\"" }
04

숫자

정수 & 부동소수

JSON에는 정수와 부동소수 값을 커버하는 단일 숫자 타입이 있습니다. 문법 수준에는 별개의 정수 타입이 없습니다 — 언어 바인딩이 값과 라이브러리에 따라 큰 정수를 int, long, float, decimal로 매핑할 수 있습니다.

json
{
  "count": 100,
  "negative": -42,
  "temperature": -273.15,
  "pi": 3.14159,
  "zero": 0,
  "negativeZero": -0
}

// Integers and floats use the same number type.
// JSON does not distinguish int from float at the syntax level.

과학적 표기

JSON은 과학적 표기를 지원합니다: 가수 뒤에 e나 E, 선택적 부호가 있는 지수(6.022e23 = 6.022 * 10^23). e와 E 모두 허용됩니다. 과학 데이터에서 매우 크거나 작은 숫자에 필수입니다.

json
{
  "avogadro": 6.022e23,
  "planck": 6.626e-34,
  "speedOfLight": 2.998e8,
  "small": 1.5E-10
}

// e or E is allowed (case-insensitive).
// 6.022e23 means 6.022 * 10^23.
// The exponent may be negative.

숫자 정밀도

JSON 숫자는 보통 IEEE 754 double로 파싱되므로, 2^53-1(9007199254740991)을 넘는 정수는 JavaScript에서 정밀도를 잃습니다. 0.1 같은 소수 값도 정확히 표현될 수 없습니다. 돈이나 임의 정밀도 정수에는 문자열로 인코딩하고 코드에서 Decimal/BigInteger 타입을 쓰세요.

json
{
  "big": 9007199254740993,
  "decimal": 0.1,
  "sum": 0.1,
  "money": 19.99
}

// JavaScript stores numbers as IEEE 754 doubles.
// Integers are safe up to 2^53 - 1 (9007199254740991).
// 0.1 + 0.2 === 0.30000000000000004 (float precision loss).

// For money or big integers, parse as string or use a Decimal type.

특수 값 (허용되지 않음)

표준 JSON은 NaN, Infinity, -Infinity를 허용하지 않습니다. 우회법: NaN에는 null, Infinity는 문자열로 인코딩, 또는 유한 센티널 값 사용. 일부 직렬화기(Python의 json 기본값, JSON5)는 이들을 확장으로 내보내지만 출력이 비표준이며 엄격한 파서가 거부할 수 있습니다.

json
// NaN, Infinity, and -Infinity are NOT valid JSON.

// INVALID:
// { "x": NaN }
// { "y": Infinity }
// { "z": -Infinity }

// Common workarounds:
{
  "x": null,           // represent NaN/null
  "y": "Infinity",     // encode as a string
  "z": 1.7976931348623157e308  // use a finite max
}

// Many serializers (e.g., Python json) accept these as extensions
// but the output is not standard JSON.

숫자 형식

유효한 JSON 숫자: 선택적 마이너스, 정수부(0을 제외하고 선행 0 없음), 선택적 소수부, 선택적 지수. 16진수(0x), 2진수(0b), 8진수, 언더스코어, 선행 +, 선행 0, 양쪽에 숫자가 없는 점은 모두 무효입니다.

json
// VALID JSON numbers:
42
-7
0
3.14
-0.5
6.022e23
1.5E-10
100.00

// INVALID:
007        // leading zero
.5         // no leading digit
5.         // no trailing digit after dot
+5         // leading plus sign
0x1F       // hex
0b101      // binary
1_000      // underscores

큰 숫자 & BigInt

2^53-1을 넘는 값(예: Twitter snowflake ID, 64비트 정수, 큰 잔액)에는 정밀도 손실을 피하려 문자열로 인코딩하세요. JSON.parse의 reviver로 숫자를 BigInt로 변환해야 한다면, BigInt는 replacer 없이는 JSON.stringify로 재직렬화할 수 없음을 기억하세요 — 전송 계층에서는 문자열이 더 안전합니다.

json
{
  "snowflake": "1234567890123456789",
  "timestamp": 1696000000000,
  "balance": "99999999999999999999"
}

// Numbers above 2^53-1 lose precision in JS.
// Use STRINGS for IDs, snowflakes, and big integers.

// In JavaScript, parse with a reviver:
// JSON.parse(str, (k, v) =>
//   typeof v === "number" && v > Number.MAX_SAFE_INTEGER
//     ? BigInt(v) : v);  // careful: BigInt can't be in JSON.stringify

// Better: keep them as strings on the wire.
05

불리언 & Null

불리언 값

JSON 불리언은 맨 키워드 true와 false입니다. 따옴표가 붙은 'true'/'false'는 문자열입니다. JSON에는 문법 수준의 truthy/falsy 개념이 없습니다 — 1, 0, yes, no, on, off는 모두 문자열이나 숫자지 불리언이 아닙니다. 애플리케이션 코드에서 변환하세요.

json
{
  "enabled": true,
  "disabled": false,
  "isPublic": true,
  "isActive": false
}

// Only two boolean values: true and false (lowercase, unquoted).
// "true" (quoted) is a STRING, not a boolean.
// 1/0, yes/no, on/off are NOT booleans.

null의 의미

JSON null은 값의 의도적 부재를 신호합니다. 없는 키(객체에 키가 없음), 빈 문자열 '', 0, false, 빈 컬렉션과 구별됩니다. 필드가 존재하지만 값이 없을 때 null을 쓰고, 필드 자체가 해당하지 않을 때는 키를 생략하세요.

json
{
  "middleName": null,
  "deletedAt": null,
  "parent": null,
  "optional": null
}

// null means "no value" or "intentionally absent".
// Distinct from:
//   - missing key (key not present at all)
//   - empty string ""
//   - 0 or false
//   - empty array [] or object {}

null vs 빈 값 vs 없음

세 가지 구별되는 상태: 빈 값을 가진 키(""), 명시적으로 null인 키, 없는 키. JavaScript에서 undefined는 키가 없다는 뜻이고 null은 존재하지만 값이 없다는 뜻입니다. API는 선택적 필드에 어느 관례를 쓰는지 문서화해야 합니다.

json
{
  "name": "Alice",
  "nickname": "",          // empty string (present, empty)
  "middleName": null,      // explicit null (present, no value)
  // "maidenName"           // missing (key not in object)
}

// In JavaScript:
//   obj.nickname === ""           // true
//   obj.middleName === null       // true
//   obj.maidenName === undefined  // true (key absent)
//   "maidenName" in obj           // false

// Choose deliberately: null vs "" vs missing.

조건에서의 불리언 사용

JSON 불리언을 소비할 때 false와 없음을 구분해야 하면 truthy 검사보다 엄격한 비교(=== true)를 선호하세요. API 응답에는 false일 때도 불리언 필드를 항상 포함하세요 — 생략하면 클라이언트가 기본값을 추측해야 합니다.

json
{
  "isAdmin": true,
  "canEdit": false,
  "active": true
}

// In application code (JavaScript):
// if (user.isAdmin) { ... }       // truthy check
// const canEdit = user.canEdit === true;  // strict boolean check

// Be careful: a missing 'canEdit' key is undefined (falsy),
// but explicit false is also falsy. Distinguish if needed.

// API design: always send the boolean, even when false.

흔한 함정

흔한 함정: true/false/null에 따옴표를 붙이면 문자열이 됩니다; True/TRUE/None(Python)이나 대소문자가 틀린 true/false는 무효입니다; JSON에는 undefined가 없습니다(null만). 유효한 형태는 소문자 따옴표 없는 키워드 true, false, null뿐입니다.

json
// Pitfall 1: quoting booleans/null
// { "x": "true" }   -> x is a STRING, not a boolean
// { "y": "null" }   -> y is a STRING, not null

// Pitfall 2: wrong case
// { "x": True }     -> INVALID (Python-style, not JSON)
// { "x": TRUE }     -> INVALID
// { "x": None }     -> INVALID

// Pitfall 3: confusing null with undefined
//   null exists in JSON; undefined does NOT.

// Correct:
{ "x": true, "y": null }
06

배열

배열 기본

JSON 배열은 [ ]로 감싸고 쉼표로 구분된 값들을 가진 순서 있고 0 인덱스의 목록입니다. 빈 배열과 단일 요소 배열도 유효합니다. 순서는 의미가 있으며 파서가 보존합니다. 끝 쉼표는 허용되지 않습니다.

json
{
  "numbers": [1, 2, 3, 4, 5],
  "strings": ["a", "b", "c"],
  "booleans": [true, false, true],
  "empty": [],
  "single": [42]
}

// Arrays are ordered, zero-indexed lists in [ ].
// Elements are separated by commas (no trailing comma).
// Empty arrays [] and single-element arrays are valid.

혼합 타입 배열

JSON 배열은 합법적으로 혼합 타입을 담을 수 있습니다([1, 'two', true, null]). 유효하지만 흔히 취약한 스키마 설계를 나타냅니다. 동질 배열(모두 문자열, 모두 객체)이 검증, 문서화, 소비가 더 쉽습니다. 요소 타입 강제에는 스키마를 쓰세요.

json
{
  "mixed": [1, "two", true, null, 3.14],
  "nested": [[1, 2], "x", { "a": 1 }]
}

// JSON arrays CAN hold values of different types.
// This is valid but often a sign of weak schema design.
// Prefer homogeneous arrays for clarity and validation.

중첩 배열

배열은 임의 깊이로 중첩될 수 있습니다 — 행렬, 격자, 트리 구조에 유용합니다. JSON은 중첩 배열의 길이가 같다고 강제하지 않습니다('가지런하지 않은' 배열도 유효). 직사각형 행렬이 필요하면 스키마나 애플리케이션 코드로 강제하세요.

json
{
  "matrix": [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
  "ragged": [[1, 2], [3, 4, 5], [6]]
}

// Arrays can nest arbitrarily deep.
// JSON does not enforce rectangular shape—use a schema if needed.

객체의 배열

객체의 배열이 레코드 목록(사용자, 제품, 게시물)의 가장 흔한 패턴입니다. 각 요소가 보통 같은 모양이지만 JSON은 이를 강제하지 않습니다 — 모든 요소가 준수하는지 검증하려 스키마(JSON Schema의 'items')를 쓰세요.

json
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" },
    { "id": 3, "name": "Carol" }
  ],
  "empty": []
}

// A very common pattern: a list of records.
// Each element is an object with the same shape.

빈 배열 & 단일 요소 배열

빈 배열 []과 단일 요소 배열은 유효합니다. API 설계에서는 [](있음, 빈 목록)과 null(있음, 목록 없음), 없는 키(필드가 해당하지 않음)를 구분하세요. '항목 없음'에 []를 반환하는 것이 보통 null보다 친절합니다.

json
{
  "empty": [],
  "single": [42],
  "tags": [],
  "items": ["one"]
}

// Both forms are valid.
// Distinguish [] from null and from a missing key:
//   "tags": []      -> present, empty list
//   "tags": null    -> present, no list
//   // (no tags)    -> missing key

코드에서의 배열 접근

파싱 후 JSON 배열은 당신의 언어의 네이티브 배열/리스트가 됩니다(JS Array, Python list, Java List 등). 표준 인덱스 접근, length, 순회를 쓰세요. 경계와 타입 안전은 당신의 책임입니다 — JSON 자체는 요소 타입을 강제하지 않습니다.

json
{
  "list": ["a", "b", "c"]
}

// JavaScript:
//   const arr = JSON.parse(json).list;
//   arr[0]            // "a"
//   arr.length        // 3
//   arr.includes("b") // true
//   arr.map(x => x.toUpperCase())  // ["A", "B", "C"]

// Python:
//   data = json.loads(json_str)
//   data["list"][0]   # "a"
//   len(data["list"]) # 3
07

객체

객체 기본

JSON 객체는 { }로 감싼 키/값 쌍의 비순서 모음입니다. 키는 큰따옴표 문자열이어야 하고, 값은 어떤 JSON 타입이든 될 수 있습니다. 쌍은 쉼표로 구분되며 끝 쉼표는 없습니다. 객체가 가장 흔한 최상위 JSON 구조입니다.

json
{
  "id": 1,
  "name": "Alice",
  "email": "[email protected]",
  "active": true
}

// Objects are unordered { } collections of key/value pairs.
// Keys MUST be double-quoted strings.
// Pairs are comma-separated (no trailing comma).

키 네이밍 규칙

JSON 키는 빈 문자열, 공백, 점, 숫자를 포함해 어떤 큰따옴표 문자열이든 될 수 있습니다. 그러나 API 명확성을 위해 일관된 camelCase, snake_case, kebab-case를 권합니다. 공개 API에서는 공백, 점(경로 문법과 충돌), 빈 키를 피하세요.

json
{
  "simple": "ok",
  "with-dash": "ok",
  "with_underscore": "ok",
  "with.dot": "ok",
  "with space": "ok (but avoid)",
  "123numeric": "ok (but avoid)",
  "": "empty key is valid"
}

// Keys are arbitrary strings (double-quoted).
// Convention: use camelCase, snake_case, or kebab-case consistently.
// Avoid empty keys and keys with spaces/dots in APIs.

중첩 객체

객체는 임의 깊이로 중첩될 수 있습니다 — 계층 데이터에 유용합니다. 깊은 중첩은 유효하지만 가독성을 해치고 결합도를 높입니다. 공개 API에는 더 평탄한 구조나 깊게 중첩된 트리 대신 참조(ID)를 권합니다.

json
{
  "user": {
    "name": "Alice",
    "address": {
      "street": "123 Main St",
      "city": "NYC",
      "geo": { "lat": 40.7, "lng": -74.0 }
    }
  }
}

// Objects can nest arbitrarily deep.
// Deep nesting is valid but can hurt readability—flatten when sensible.

배열이 있는 객체

객체(키잉된 필드용)와 배열(순서 있는 목록용)의 결합이 거의 모든 실제 데이터를 모델링합니다. 흔한 패턴은 중첩 객체의 배열을 감싼 객체입니다(주문들을 가진 사용자). 기대 모양을 문서화하고 검증하려 스키마를 쓰세요.

json
{
  "user": {
    "name": "Alice",
    "roles": ["admin", "user"],
    "orders": [
      { "id": 1, "total": 19.99 },
      { "id": 2, "total": 5.99 }
    ]
  }
}

// Combining objects and arrays models most real-world data.

멤버 순서

JSON 스펙은 객체를 비순서로 다룹니다. 실제로는 대부분의 현대 파서(JavaScript V8, Python 3.7+, Java LinkedHashMap)가 삽입 순서를 유지하지만, 정확성을 위해 이에 의존해서는 안 됩니다. 해싱이나 서명에 순서가 중요하면 명시적으로 키를 정렬하세요.

json
{
  "z": 1,
  "a": 2,
  "m": 3
}

// JSON objects are SPECIFIED as unordered.
// In practice, most parsers (JS, Python 3.7+) preserve insertion order.
// DO NOT rely on order for correctness—sort keys if order matters.

// Sorting keys (e.g., for stable hashing):
//   JSON.stringify(obj, Object.keys(obj).sort())

중복 키

JSON 스펙은 중복 키를 금지하지 않지만 동작은 정의되지 않았습니다 — 대부분의 파서가 마지막 값을 유지하고 일부는 첫 값을 유지합니다. 중복 키는 미묘한 버그의 흔한 원인입니다. JSON Schema는 uniqueKeys를 강제할 수 있고, 린터와 엄격한 파서가 거부할 수 있습니다.

json
// Technically valid JSON, but behavior is UNDEFINED:
{
  "name": "Alice",
  "name": "Bob"
}

// Most parsers keep the LAST value ("Bob"),
// but some keep the first. Avoid duplicate keys!

// JSON Schema (draft 2019-09+) has 'uniqueKeys' to forbid them.
// JSON.parse in JS keeps the last value (object property override).
08

중첩 구조

깊은 중첩

JSON은 임의 중첩 깊이를 허용하지만, 매우 깊은 구조는 가독성을 해치고 파서 한도에 걸릴 수 있습니다(서비스 거부 공격을 막으려고 많은 곳이 깊이 상한, 예: 1000, 을 둡니다). 깊게 계층적인 데이터에는 ID/참조를 가진 더 평탄한 구조를 권합니다.

json
{
  "a": {
    "b": {
      "c": {
        "d": {
          "e": { "value": 42 }
        }
      }
    }
  }
}

// Nesting depth is theoretically unlimited.
// Many parsers impose a limit (e.g., 1000) to prevent DoS.
// Deep nesting hurts readability—consider flattening or references.

실제 사례

실제 JSON은 엔티티와 관계를 모델링하려고 객체와 배열을 섞습니다. 이 주문 예제는 customer, items(객체의 배열), shipping을 중첩합니다. 모양을 문서화하려 스키마를 쓰세요; 가독성을 위해 중첩은 적당히 유지하세요.

json
{
  "order": {
    "id": "ord-123",
    "customer": {
      "id": "cus-1",
      "name": "Alice",
      "email": "[email protected]"
    },
    "items": [
      { "sku": "A1", "qty": 2, "price": 9.99 },
      { "sku": "B2", "qty": 1, "price": 19.99 }
    ],
    "shipping": {
      "address": { "city": "NYC", "zip": "10001" },
      "method": "express"
    },
    "total": 39.97
  }
}

트리 구조

트리는 재귀적으로 모델링됩니다: 각 노드가 값과 자식 노드의 배열을 갖습니다. 이 패턴은 파일시스템, 조직도, AST에서 나타납니다. 순환을 조심하세요 — JSON에는 참조 문법이 없으므로, 순환 그래프는 ID를 쓰거나 부모 포인터가 있는 평탄한 목록으로 직렬화해야 합니다.

json
{
  "name": "root",
  "children": [
    {
      "name": "child-a",
      "children": [
        { "name": "grandchild-1", "children": [] },
        { "name": "grandchild-2", "children": [] }
      ]
    },
    { "name": "child-b", "children": [] }
  ]
}

// Recursive structures: a node contains an array of child nodes.

중첩 값 접근

깊게 중첩된 값 접근은 중간 키가 없으면 TypeError/KeyError를 냅니다. 선택적 체이닝(JS의 ?.와 ??)이나 기본값이 있는 체이닝 .get()(Python)을 쓰세요. lodash.get이나 jq 같은 라이브러리가 깊은 추출을 단순화하고 기본값을 제공합니다.

json
{
  "user": { "address": { "city": "NYC" } }
}

// JavaScript (optional chaining):
//   const city = data?.user?.address?.city ?? "unknown";

// Python:
//   city = data.get("user", {}).get("address", {}).get("city", "unknown")

// Deep access without guards throws on missing keys.
// Use optional chaining or a helper like lodash.get.

중첩 데이터 평탄화

중첩 객체 평탄화(예: { user: { name } } 대신 'user.name')는 환경 변수, 폼 필드, 검색 색인의 접근을 단순화합니다. 대가는 구조의 손실과 더 어려운 왕복 변환입니다. 평탄화/복원에는 라이브러리(flat, lodash)를 쓰세요.

json
// Nested form:
{ "user": { "name": "Alice", "city": "NYC" } }

// Flattened form (dot notation):
{ "user.name": "Alice", "user.city": "NYC" }

// Flattened form (separate keys):
{ "userName": "Alice", "userCity": "NYC" }

// Use cases: environment variables, form fields, search indexing.
// Trade-off: simpler access vs. loss of structure.
09

JSON Schema

스키마 기본

JSON Schema는 JSON 문서를 기술하고 검증하는 JSON 어휘입니다. 루트가 $schema(초안 버전)와 type을 선언합니다. properties가 타입과 함께 필드를 나열하고, required가 필수 키를 나열합니다. Ajv(JS)나 jsonschema(Python) 같은 검증기가 준수 여부를 확인합니다.

json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/user.json",
  "title": "User",
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 }
  },
  "required": ["name"]
}

타입 검증

'type' 키워드가 값의 JSON 타입을 검증합니다: string, number, integer, boolean, null, array, object. 단일 타입이나 배열이 될 수 있습니다(예: 선택적 널러블 문자열에는 ['string', 'null']). 'integer'는 소수부가 없는 숫자와 매칭됩니다.

json
{
  "type": "object",
  "properties": {
    "name":   { "type": "string" },
    "age":    { "type": "integer" },
    "active": { "type": "boolean" },
    "score":  { "type": "number" },
    "tags":   { "type": "array", "items": { "type": "string" } },
    "meta":   { "type": "object" },
    "middle": { "type": ["string", "null"] }
  }
}

// 'type' can be a single type or an array of allowed types.

문자열 제약

문자열 제약: minLength, maxLength, pattern(정규식), enum(허용 값), format('email', 'uri', 'date-time', 'ipv4' 같은 의미 힌트). 'format'은 기본적으로 어노테이션 전용입니다 — 검증기가 강제하려면 옵트인해야 합니다. 엄격한 정규식 검증에는 pattern을 쓰세요.

json
{
  "type": "object",
  "properties": {
    "email": {
      "type": "string",
      "format": "email",
      "maxLength": 254
    },
    "username": {
      "type": "string",
      "pattern": "^[a-zA-Z0-9_]{3,20}$",
      "minLength": 3,
      "maxLength": 20
    },
    "bio": { "type": "string", "maxLength": 500 }
  }
}

// 'format' is a semantic hint (email, uri, date, ipv4).
// 'pattern' is a regular expression.

숫자 제약

숫자 제약: minimum, maximum(포함), exclusiveMinimum, exclusiveMaximum, multipleOf. 'integer' 타입에서는 값에 소수부가 없어야 합니다. 제약을 결합해 범위를 모델링하세요(예: 1에서 5까지의 평점).

json
{
  "type": "object",
  "properties": {
    "age":   { "type": "integer", "minimum": 0, "maximum": 150 },
    "price": { "type": "number", "minimum": 0, "exclusiveMinimum": 0 },
    "rating":{ "type": "integer", "minimum": 1, "maximum": 5 },
    "count": { "type": "integer", "multipleOf": 5 }
  }
}

// minimum/maximum are inclusive;
// exclusiveMinimum/exclusiveMaximum are exclusive.

객체 & 배열 제약

배열 제약: items(요소 스키마), minItems, maxItems, uniqueItems. 객체 제약: required(필수 키), properties(필드 스키마), additionalProperties(false면 여분 키 금지, 또는 그들의 스키마), minProperties, maxProperties.

json
{
  "type": "object",
  "properties": {
    "id":   { "type": "integer" },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1,
      "maxItems": 10,
      "uniqueItems": true
    }
  },
  "required": ["id"],
  "additionalProperties": false
}

// minItems/maxItems/uniqueItems constrain arrays.
// required lists mandatory keys; additionalProperties
// controls whether extra keys are allowed.

고급 검증

고급 JSON Schema: oneOf/anyOf/allOf가 서브스키마를 결합하고, $ref가 재사용 정의를 참조하며, if/then/else가 조건부 검증을 적용하고, const가 정확한 값을 요구하며, enum이 허용 값을 나열합니다. 이들로 풍부한 제약과 재사용 타입을 표현합니다.

json
{
  "oneOf": [
    { "type": "string" },
    { "type": "integer" }
  ],
  "definitions": {
    "address": {
      "type": "object",
      "properties": { "city": { "type": "string" } }
    }
  },
  "properties": {
    "home": { "$ref": "#/definitions/address" },
    "work": { "$ref": "#/definitions/address" }
  },
  "if":   { "properties": { "type": { "const": "vip" } } },
  "then": { "required": ["discount"] }
}

// oneOf/anyOf/allOf combine schemas.
// $ref reuses definitions; if/then/else is conditional.
10

JSONPath

JSONPath 문법

JSONPath는 XPath에서 영감을 받은 JSON 쿼리 언어입니다. '$'가 루트이고, '.'가 자식을 선택하며, '[index]'가 배열 요소를 선택하고, '*'가 와일드카드이며, '..'가 재귀 하강입니다. jsonpath-plus(JS)나 jsonpath-ng(Python) 같은 라이브러리가 구현합니다.

json
// JSONPath queries JSON like XPath queries XML.

// Sample data:
{
  "store": {
    "book": [
      { "category": "fiction", "price": 12.99 },
      { "category": "web",     "price": 29.99 }
    ]
  }
}

// Common JSONPath expressions:
$.store.book[0].category      // "fiction"
$.store.book[*].price         // [12.99, 29.99]
$..price                      // all prices anywhere
$.store..category             // all categories under store

루트 & 자식

'$'가 루트를 참조합니다. '.'가 이름으로 자식을 선택하고, '[]'는 점, 공백, 따옴표가 있는 키를 다루는 대괄호 대안입니다. '[index]'가 배열 요소를 선택합니다(0 기반); 일부 구현은 끝에서부터 세는 음수 인덱스를 지원합니다.

json
// '$' = root object/array
// '.' or '[]' = child

$.user.name              // dot notation
$['user']['name']        // bracket notation (use for special chars)
$.users[0]               // first element of users array
$.users[-1]              // last element (some implementations)

// Use bracket notation when keys contain dots, spaces, or quotes:
$['user.name']
$['first name']

재귀 하강

'..'(재귀 하강)는 어떤 깊이에서든 키나 요소를 매칭합니다. '$..price'는 나타나는 곳마다 모든 'price' 값을 반환합니다. '$..*'은 모든 노드를 반환합니다. 정확한 경로를 모를 때 크거나 깊게 중첩된 JSON 검색에 매우 유용합니다.

json
{
  "a": { "b": { "c": 1 }, "c": 2 }
}

// '..' searches at all depths:
$..c                      // [1, 2] (all 'c' keys anywhere)
$..a                      // all 'a' keys
$..*                      // every node (everything)

// Useful for finding a key without knowing the exact path:
$..price                  // every price, no matter how nested

필터 표현식

필터는 '@'가 현재 항목을 가리키는 [?(expression)]을 씁니다. 지원 연산자는 구현마다 다르지만 보통 ==, !=, <, <=, >, >=, &&(and), ||(or), 때때로 정규식용 =~을 포함합니다. length()와 contains() 같은 함수가 힘을 더합니다.

json
// Filter with [?(expression)]:

$.store.book[?(@.price < 20)]            // books under 20
$.store.book[?(@.category == 'web')]     // web books
$.store.book[?(@.price < 30 && @.category == 'web')]

// '@' refers to the current item being filtered.
// Operators: == != < <= > >= && || =~ (regex in some impls)
// Functions: length(), contains(), matches()

와일드카드

'*'는 객체의 모든 자식이나 배열의 모든 요소에 매칭되는 와일드카드입니다. '$.users[*].name'이 모든 사용자의 'name'을 반환합니다. '$..*'은 모든 노드를 반환합니다. 결과는 매칭의 배열로 반환됩니다 — 하나뿐이어도.

json
{
  "users": [
    { "name": "Alice", "age": 30 },
    { "name": "Bob",   "age": 25 }
  ]
}

// '*' matches all elements/children:
$.users[*]               // all user objects
$.users[*].name          // ["Alice", "Bob"]
$.users[0].*             // all values of first user: ["Alice", 30]
$..*                     // every node in the document

// Wildcards return arrays of matches.

흔한 함수 & 예제

JSONPath 함수는 구현마다 다릅니다: length(), min(), max(), avg(), sum(), contains(), matches()가 흔합니다. 강력한 쿼리를 위해 필터와 재귀 하강을 결합하세요. CLI 작업에는 jq가 사실상 표준이며 약간 다른 문법을 씁니다.

json
// length(): array length or string length
$.users.length()                    // number of users
$.store.book[?(@.title.length() > 10)]

// min(), max(), avg(), sum() (some implementations)
$.store.book..price.min()

// Realistic query: titles of cheap web books
$.store.book[?(@.price < 20 && @.category == 'web')].title

// Tools: jq (CLI), jsonpath-plus (JS), jsonpath-ng (Python),
//        Jayway (Java), GoJSONQ (Go)
11

JSON vs XML & YAML

JSON vs XML 문법

JSON은 더 가볍습니다(닫는 태그 없음, 숫자/불리언/null의 네이티브 타입)이고 대부분의 언어 자료구조에 직접 매핑됩니다. XML은 더 무겁지만 풍부합니다: 속성, 네임스페이스, 혼합 콘텐츠, 스키마(XSD), 변환(XSLT). JSON이 웹 API를 지배하고, XML은 기업/SOAP에 남아 있습니다.

json
// JSON:
{
  "name": "Alice",
  "age": 30,
  "hobbies": ["reading", "coding"]
}

<!-- XML: -->
<person>
  <name>Alice</name>
  <age>30</age>
  <hobbies>
    <hobby>reading</hobby>
    <hobby>coding</hobby>
  </hobbies>
</person>

// JSON: lighter, no closing tags, types (number/boolean/null).
// XML:  heavier, supports attributes, namespaces, mixed content.

JSON vs YAML 문법

YAML은 중괄호/따옴표 대신 들여쓰기를 쓰고 주석, 여러 줄 문자열, 앵커/별칭을 지원합니다. JSON은 더 엄격하지만(따옴표 필수, 주석 없음) 더 빠르고 보편적입니다. YAML은 JSON 상위집합입니다 — 모든 유효한 JSON 파일이 유효한 YAML이기도 합니다.

json
# YAML:
name: Alice
age: 30
hobbies:
  - reading
  - coding

// JSON (equivalent):
{
  "name": "Alice",
  "age": 30,
  "hobbies": ["reading", "coding"]
}

// YAML: no quotes/braces, indentation-based, supports comments.
// JSON: stricter, faster to parse, ubiquitous in APIs.

JSON → YAML 변환

JSON을 YAML로 변환하는 것은 YAML이 JSON 상위집합이라 간단합니다. Python의 yaml.dump와 Node의 js-yaml이 처리합니다. 결과는 들여쓰기를 쓰고 (대부분) 따옴표가 없습니다. YAML의 주석과 여러 줄 문자열은 JSON에서 왕복되지 않습니다(JSON에는 없음).

json
// JSON input:
{ "name": "Alice", "roles": ["admin", "user"] }

// YAML output:
name: Alice
roles:
  - admin
  - user

// Python:
//   import yaml, json
//   yaml.dump(json.loads(json_str), sort_keys=False)

// Node.js:
//   const yaml = require('js-yaml');
//   yaml.dump(JSON.parse(jsonStr));

YAML → JSON 변환

YAML을 JSON으로 변환하는 것은 단순한 YAML에선 되지만 YAML 고유 기능을 잃습니다: 주석, 앵커/별칭, 다중 문서 스트림, 태그, 복잡한 키. 커스텀 태그로 인한 임의 코드 실행을 피하려 yaml.safe_load를 쓰세요. 결과는 표준 JSON입니다.

json
# YAML input:
server:
  host: localhost
  port: 8080
  debug: true

// JSON output:
{
  "server": {
    "host": "localhost",
    "port": 8080,
    "debug": true
  }
}

// Python:
//   import yaml, json
//   json.dumps(yaml.safe_load(yaml_str), indent=2)

// Watch for YAML-specific features: anchors, tags, multi-docs.

데이터 모델링 차이

JSON은 데이터를 객체와 배열로 모델링합니다 — 속성이나 네임스페이스가 없습니다. XML은 속성, 네임스페이스, 혼합 콘텐츠, 풍부한 스키마를 더합니다. YAML은 주석, 앵커, 다중 문서 지원을 더합니다. TOML은 테이블이 있는 설정 파일을 타깃합니다. 필요에 따라 고르세요: API(JSON), 문서(XML), 설정(YAML/TOML).

json
// JSON: objects and arrays, no attributes.
//   Attribute-style metadata needs a convention (e.g., @_prefix).

// XML: elements + attributes, namespaces, mixed content.
//   <book id="b1" category="web"><title>...</title></book>

// YAML: maps, sequences, scalars, anchors, multi-doc.
//   Supports comments and multi-line strings natively.

// TOML: tables + key/value, designed for config files.
//   Best for configuration; not ideal for nested data.

각 형식의 사용 시점

웹 API와 NoSQL 저장에는 JSON(만능, 빠름). 기업 서비스, 문서 중심 데이터(SVG, XHTML), 풍부한 스키마에는 XML. 주석과 가독성 덕에 사람이 쓰는 설정(CI/CD, docker-compose)에는 YAML. 작은 설정 파일에는 TOML. 형식을 사용 사례에 맞추세요.

json
// Use JSON when:
//   - building web/REST APIs (universal browser support)
//   - storing structured data (NoSQL databases)
//   - configuration with simple needs (package.json)

// Use XML when:
//   - enterprise/SOAP web services
//   - documents with mixed content (SVG, XHTML, DocBook)
//   - you need schemas, namespaces, or XSLT transforms

// Use YAML when:
//   - human-written config (CI/CD, docker-compose)
//   - you need comments and multi-line strings

// Use TOML when:
//   - small config files (Cargo, pyproject)
12

JavaScript에서의 파싱

JSON.parse

JSON.parse가 JSON 문자열을 JavaScript 값으로 바꿉니다. 어떤 유효한 JSON 값이든(객체, 배열, 문자열, 숫자, 불리언, null) 받습니다. 무효한 JSON은 SyntaxError를 던집니다. 신뢰할 수 없는 입력을 다룰 때는 항상 JSON.parse를 try/catch로 감싸세요.

json
// Parse a JSON string into a JavaScript value.
const json = '{"name":"Alice","age":30}';
const obj = JSON.parse(json);

console.log(obj.name); // "Alice"
console.log(obj.age);  // 30

// JSON.parse accepts a string only.
// Passing a number/boolean/object throws or coerces.
// JSON.parse("42")    === 42       (valid)
// JSON.parse("true")  === true     (valid)
// JSON.parse("null")  === null     (valid)
// JSON.parse(undefined) // throws SyntaxError

JSON.stringify

JSON.stringify가 JavaScript 값을 JSON 문자열로 바꿉니다. 함수, Symbol, undefined는 생략되고(객체에서) null이 됩니다(배열에서). BigInt는 TypeError를 던지므로 먼저 문자열로 바꾸세요. 예쁘게 인쇄하려 세 번째 인수(공백)를 쓰세요.

json
// Serialize a JavaScript value to a JSON string.
const obj = { name: "Alice", age: 30 };
const json = JSON.stringify(obj);
// '{"name":"Alice","age":30}'

// Pretty-print with 2-space indent:
JSON.stringify(obj, null, 2);
// {
//   "name": "Alice",
//   "age": 30
// }

// Functions, Symbols, and undefined are omitted.
// BigInt throws; use a replacer or String() first.

reviver 함수

JSON.parse의 reviver가 파싱 중 값을 변환합니다. 모든 키/값 쌍(키 ''인 루트 포함)에 대해 아래→위로 호출됩니다. 변환된 값을 반환하거나, 프로퍼티를 생략하려 undefined를 반환하세요. 날짜 파싱, BigInt, 커스텀 타입에 유용합니다.

json
// JSON.parse accepts a 'reviver' to transform values.
const json = '{"date":"2024-01-15","count":"42"}';

const obj = JSON.parse(json, (key, value) => {
  if (key === "date") return new Date(value);
  if (key === "count") return Number(value);
  return value;
});

// obj.date is a Date object; obj.count is a number.

// Reviver is called bottom-up for every key, including the root.

replacer 함수

JSON.stringify의 replacer가 직렬화 중 값을 필터하거나 변환합니다. 함수로서 모든 키에 호출되며 — 프로퍼티를 생략하려 undefined를 반환하세요. 배열로서 포함할 키의 허용 목록 역할을 합니다. 시크릿 삭제와 필드 선택에 유용합니다.

json
// JSON.stringify accepts a 'replacer' to filter/transform.
const obj = { name: "Alice", password: "secret", age: 30 };

// Replacer as a function:
const safe = JSON.stringify(obj, (key, value) => {
  if (key === "password") return undefined; // omit
  return value;
});
// '{"name":"Alice","age":30}'

// Replacer as an array (allowlist of keys):
JSON.stringify(obj, ["name", "age"]);
// '{"name":"Alice","age":30}'

예쁘게 인쇄

예쁘게 인쇄하려 JSON.stringify에 공백 인수를 전달하세요: 숫자(들여쓰기 깊이)나 문자열(예: '\t'). 안정적인 키 순서(해싱이나 서명에 유용)를 위해 stringify 전에 키를 정렬하세요. 예쁘게 인쇄하면서 필드를 필터하려 replacer와 결합하세요.

json
const obj = { name: "Alice", age: 30 };

// Compact (default):
JSON.stringify(obj);
// '{"name":"Alice","age":30}'

// 2-space indent:
JSON.stringify(obj, null, 2);

// Tab indent:
JSON.stringify(obj, null, "\t");

// Combine replacer and indent:
JSON.stringify(obj, ["name", "age"], 2);

// To insert a stable key order, sort keys first:
const sorted = Object.keys(obj).sort()
  .reduce((acc, k) => (acc[k] = obj[k], acc), {});
JSON.stringify(sorted, null, 2);

오류 처리

JSON.parse는 무효한 입력에서 SyntaxError를 던집니다 — 신뢰할 수 없는 데이터에는 항상 try/catch로 감싸세요. 흔한 원인: 끝 쉼표, 작은따옴표, 주석, 잘린 입력. 매우 크거나 깊게 중첩된 JSON에는 서비스 거부 공격을 막으려 스트리밍 파서나 깊이 제한을 고려하세요.

json
// Always wrap JSON.parse in try/catch for untrusted input.
function safeParse(str) {
  try {
    return { ok: true, value: JSON.parse(str) };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

// Common errors:
//   SyntaxError: Unexpected token
//   SyntaxError: Unexpected end of JSON input
//   (no undefined/NaN/Infinity accepted)

// For deeply nested untrusted JSON, limit depth to avoid DoS.
// Consider a streaming parser for very large files.
13

Python에서의 파싱

json.loads

json.loads가 JSON 문자열을 Python 객체로 파싱합니다. JSON 객체는 dict가 되고, 배열은 list, 문자열은 str, 숫자는 자동으로 int나 float, true/false는 True/False, null은 None이 됩니다. 'loads'는 'load string'입니다.

json
import json

json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)

print(data["name"])  # Alice
print(data["age"])   # 30

# loads = "load string"
# Returns Python objects: dict, list, str, int/float, bool, None
# JSON true/false/null  ->  Python True/False/None
# JSON numbers          ->  int or float (auto)

json.dumps

json.dumps가 Python 객체를 JSON 문자열로 직렬화합니다. 예쁘게 인쇄에는 indent, 유니코드 문자를 유지하려(\uXXXX 이스케이프 대신) ensure_ascii=False, 안정적인 출력에는 sort_keys=True를 쓰세요. Python의 True/False/None이 JSON의 true/false/null로 매핑됩니다.

json
import json

data = {"name": "Alice", "age": 30, "active": True}

# Compact:
json.dumps(data)
# '{"name": "Alice", "age": 30, "active": true}'

# Pretty-printed:
json.dumps(data, indent=2, ensure_ascii=False)
# {
#   "name": "Alice",
#   "age": 30,
#   "active": true
# }

# ensure_ascii=False keeps Unicode characters readable.
# sort_keys=True produces stable output.

파일 파싱

파일에는 json.load(파일 객체)와 json.dump(파일 객체)를, 문자열에는 json.loads와 json.dumps를 쓰세요. 플랫폼 기본값을 피하려 파일을 항상 encoding='utf-8'로 여세요. 큰 파일에는 더 나은 성능을 위해 ijson(스트리밍)이나 orjson(더 빠름)을 고려하세요.

json
import json

# Read from a file:
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# Write to a file:
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

# load/dump work on file objects; loads/dumps work on strings.
# Always specify encoding="utf-8" for portability.

커스텀 인코더

json.JSONEncoder를 서브클래싱하고 default()를 오버라이드해 JSON이 네이티브로 지원하지 않는 타입(datetime, set, Decimal, 커스텀 클래스)을 직렬화하세요. JSON 직렬화 가능한 표현을 반환합니다. 디코딩에는 변환을 되돌리는 커스텀 훅(object_hook)을 쓰세요.

json
import json
from datetime import datetime, date

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        if isinstance(obj, set):
            return sorted(obj)
        return super().default(obj)

data = {"now": datetime.now(), "tags": {"a", "b"}}
json.dumps(data, cls=CustomEncoder)
# '{"now": "2024-...", "tags": ["a", "b"]}'

# The default() method is called for objects json can't serialize.

오류 처리

json.loads는 무효한 입력에서 줄/열 정보와 함께 json.JSONDecodeError를 발생시킵니다. 흔한 원인: 끝 쉼표, 작은따옴표, 주석, NaN/Infinity(기본 거부), 문자열의 제어 문자. 필요하면 NaN/Infinity/-Infinity 처리에 parse_constant를 쓰세요.

json
import json

def safe_loads(s):
    try:
        return {"ok": True, "value": json.loads(s)}
    except json.JSONDecodeError as e:
        return {"ok": False, "error": str(e), "line": e.lineno, "col": e.colno}

# json.JSONDecodeError gives line and column of the error.
# Common causes: trailing commas, single quotes, comments,
#   NaN/Infinity (rejected by default), control chars in strings.

# To allow NaN/Infinity (non-standard):
json.loads('{"x": NaN}', parse_constant=lambda x: None)  # or float(x)

Decimal & DateTime 다루기

기본적으로 json은 모든 숫자를 float로 파싱해 돈 같은 소수의 정밀도를 잃습니다. 정밀도를 유지하려 parse_float=Decimal을 전달하고, Decimal을 되돌리는 default 훅으로 직렬화하세요(정밀도 유지는 str, 손실이 허용되면 float). 정확한 돈 표현에는 str을 쓰세요.

json
import json
from decimal import Decimal
from datetime import datetime

# Decimal: parse_float keeps precision (default would lose it)
data = json.loads('{"price": 19.99}', parse_float=Decimal)
print(data["price"])        # Decimal('19.99')
print(data["price"] + Decimal("0.01"))  # 20.00 exact

# Serialize Decimal back:
def encode(obj):
    if isinstance(obj, Decimal):
        return float(obj)   # or str(obj) to keep precision
    raise TypeError

json.dumps({"price": Decimal("19.99")}, default=encode)

# parse_float=float is the default; use Decimal for money.
14

Java에서의 파싱

Jackson 기본

Jackson이 가장 인기 있는 Java JSON 라이브러리입니다. ObjectMapper.readValue가 JSON을 POJO로 파싱하고, writeValueAsString이 직렬화합니다. 의존성으로 jackson-databind(그리고 jackson-core, jackson-annotations)를 추가하세요. Jackson은 빠르고 성숙하며 Spring Boot와 기본 통합됩니다.

json
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();

// Parse JSON to a Java object:
String json = "{\"name\":\"Alice\",\"age\":30}";
User user = mapper.readValue(json, User.class);

// Serialize a Java object:
String out = mapper.writeValueAsString(user);

// Pretty-print:
String pretty = mapper.writerWithDefaultPrettyPrinter()
                      .writeValueAsString(user);

// Jackson is the de facto JSON library for Java.
// Add: com.fasterxml.jackson.core:jackson-databind

Gson 기본

Gson은 Google의 JSON 라이브러리로 기본 사용에서는 Jackson보다 단순합니다. Gson.fromJson가 파싱하고, toJson이 직렬화합니다. 옵션(예쁘게 인쇄, null 직렬화, 커스텀 어댑터)에는 GsonBuilder를 쓰세요. 의존성으로 com.google.code.gson:gson을 추가하세요. Gson은 Android에서 흔합니다.

json
import com.google.gson.Gson;

Gson gson = new Gson();

// Parse:
User user = gson.fromJson(json, User.class);

// Serialize:
String out = gson.toJson(user);

// Pretty-print:
Gson pretty = new GsonBuilder().setPrettyPrinting().create();
String s = pretty.toJson(user);

// Gson (by Google) is simpler than Jackson for basic use.
// Add: com.google.code.gson:gson

JsonNode 트리 모델

Jackson의 JsonNode는 POJO 없이 JSON을 탐색하는 트리 모델입니다. get()(없으면 null 반환)이나 path()(체이닝을 위한 안전한 'missing node' 반환)를 쓰세요. asText/asInt/asBoolean에는 기본값이 있는 오버로드가 있습니다. 스키마를 모르거나 바뀔 때 유용합니다.

json
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);

String name = root.get("name").asText();     // "Alice"
int age = root.get("age").asInt();            // 30
JsonNode hobbies = root.get("hobbies");       // array
for (JsonNode h : hobbies) {
    System.out.println(h.asText());
}

// get() returns null for missing keys; path() returns a
// 'missing node' that you can chain safely.
String city = root.path("address").path("city").asText("unknown");

커스텀 역직렬화

커스텀 JsonDeserializer가 비표준 JSON 인코딩(예: 돈용 '$19.99')을 처리합니다. 필드에 @JsonDeserialize(using = ...)을 어노테이션하거나 타입에 SimpleModule을 등록하세요. 커스텀 직렬화에는 JsonSerializer를 쓰세요. 이로써 POJO가 파싱 로직으로부터 깨끗하게 유지됩니다.

json
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.*;
import java.io.IOException;

public class MoneyDeserializer extends JsonDeserializer<Double> {
    @Override
    public Double deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {
        String s = p.getText();           // e.g. "$19.99"
        return Double.parseDouble(s.replaceAll("[^0-9.]", ""));
    }
}

// Annotate the field:
//   @JsonDeserialize(using = MoneyDeserializer.class)
//   public double price;

// Or register a module for a type.

스트리밍 API

Jackson의 스트리밍 API(JsonParser/JsonGenerator)는 상수 메모리로 토큰 단위로 JSON을 읽고 씁니다 — 거대한 파일에 이상적입니다. 파싱 루프를 직접 제어하며 skipChildren()으로 서브트리를 건너뛸 수 있습니다. 실제로 필요한 부분은 트리나 POJO 모델과 짝지으세요.

json
import com.fasterxml.jackson.core.*;

// Jackson streaming: low memory, fast, for huge files.
JsonFactory f = new JsonFactory();
try (JsonParser p = f.createParser(new File("huge.json"))) {
    while (p.nextToken() != JsonToken.END_OBJECT) {
        String field = p.getCurrentName();
        if ("name".equals(field)) {
            p.nextToken();
            System.out.println(p.getText());
        }
        // skip complex values you don't need:
        // p.skipChildren();
    }
}

// Use streaming for files that won't fit in memory.
15

PHP에서의 파싱

json_encode

json_encode가 PHP 값을 JSON으로 직렬화합니다. PHP 배열은 JSON 객체(연상)나 배열(순차)이 됩니다. 흔한 flag: JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE(읽기 쉬운 유니코드 유지), JSON_UNESCAPED_SLASHES(/를 이스케이프하지 않음). flag는 | 연산자로 결합하세요.

json
<?php
$data = ["name" => "Alice", "age" => 30, "active" => true];

// Compact (default):
$json = json_encode($data);
// {"name":"Alice","age":30,"active":true}

// Pretty-print:
$pretty = json_encode($data, JSON_PRETTY_PRINT);

// Keep Unicode readable (don't escape to \uXXXX):
$unicode = json_encode($data, JSON_UNESCAPED_UNICODE);

// Combine flags with |:
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
           | JSON_UNESCAPED_SLASHES);

json_decode

json_decode가 JSON을 PHP로 파싱합니다. 두 번째 인수가 결과를 제어합니다: true는 연상 배열, false(기본값)는 stdClass 객체를 반환합니다. 접근 스타일에 따라 고르세요($arr['key'] vs $obj->key). 비순차 키를 가진 PHP 배열은 JSON 객체가 됩니다.

json
<?php
$json = '{"name":"Alice","age":30,"hobbies":["reading"]}';

// Default: returns associative array OR object (stdClass)
$data = json_decode($json);
echo $data->name;            // Alice

// Force associative array:
$arr = json_decode($json, true);
echo $arr["name"];           // Alice

// The second argument (assoc) controls array vs object.
// PHP objects become stdClass instances by default.

오류 처리

PHP의 json_decode는 기본적으로 예외를 던지지 않습니다 — 파싱 후 json_last_error()와 json_last_error_msg()를 확인하세요. JSON_THROW_ON_ERROR(PHP 7.3+)를 전달하면 더 깔끔하게 JsonException을 던집니다. 흔한 오류: 끝 쉼표, 작은따옴표, 무효한 UTF-8.

json
<?php
$json = '{invalid json}';
$data = json_decode($json);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Parse error: " . json_last_error_msg();
    // e.g., "Syntax error"
}

// PHP does not throw on JSON errors; check json_last_error().
// Common errors: trailing comma, single quotes, invalid UTF-8.

// To throw exceptions instead:
try {
    $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo $e->getMessage();
}

예쁘게 인쇄 & flag

흔한 json_encode flag: JSON_PRETTY_PRINT(들여쓰기), JSON_UNESCAPED_UNICODE(읽기 쉬운 비 ASCII 유지), JSON_UNESCAPED_SLASHES(/를 이스케이프하지 않음), JSON_NUMERIC_CHECK(숫자 문자열을 숫자로 변환), JSON_THROW_ON_ERROR(실패 시 예외). |로 결합하세요.

json
<?php
$data = ["path" => "C:\\Users", "url" => "https://x.com/"];

// Default escapes / and non-ASCII:
json_encode($data);
// {"path":"C:\\Users","url":"https:\/\/x.com\/"}

// Cleaner output:
json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
           | JSON_PRETTY_PRINT);
// {
//     "path": "C:\\Users",
//     "url": "https://x.com/"
// }

// JSON_NUMERIC_CHECK converts numeric strings to numbers:
json_encode(["id" => "42"], JSON_NUMERIC_CHECK);  // {"id":42}

커스텀 직렬화

객체가 인코딩되는 방식을 제어하려 JsonSerializable을 구현하고 jsonSerialize()를 정의하세요. 필드 삭제(예: 비밀번호 생략), 키 이름 바꾸기, 직렬화 중 파생 값 계산의 가장 깔끔한 방법입니다. 메서드는 어떤 JSON 직렬화 가능 구조든 반환합니다.

json
<?php
class User implements JsonSerializable {
    public $name;
    public $password;

    public function __construct($name, $password) {
        $this->name = $name;
        $this->password = $password;
    }

    public function jsonSerialize(): mixed {
        return [
            "name" => $this->name,
            // omit password for security
        ];
    }
}

echo json_encode(new User("Alice", "secret"));
// {"name":"Alice"}

// JsonSerializable lets the class control its JSON form.
16

JSON:API 명세

문서 구조

JSON:API는 일관된 JSON API 구축을 위한 명세입니다. 문서는 최상위 'jsonapi' 버전 객체, 기본 'data' 리소스, 선택적 'included' 관련 리소스, 비표준 정보용 'meta', 페이징용 'links', 실패용 'errors'를 갖습니다. 미디어 타입은 application/vnd.api+json입니다.

json
{
  "jsonapi": { "version": "1.1" },
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API Basics"
    },
    "relationships": {
      "author": { "data": { "type": "people", "id": "9" } }
    }
  },
  "included": [
    { "type": "people", "id": "9", "attributes": { "name": "Jane" } }
  ]
}

// JSON:API is a convention for building JSON APIs.
// Top-level keys: jsonapi, data, errors, meta, links, included.

리소스 객체

JSON:API 리소스 객체는 'type'(리소스 종류)과 'id'(문자열 식별자), 그리고 'attributes'(데이터)와 선택적 'relationships'(다른 리소스로의 링크)와 'links'(self 같은 URL)를 갖습니다. ID는 문자열이어야 합니다. type과 id는 attributes에 나타나서는 안 됩니다.

json
{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "Hello",
      "published": true,
      "views": 42
    },
    "links": {
      "self": "/articles/1"
    }
  }
}

// Every resource has a 'type' (string) and 'id' (string).
// 'attributes' holds data; 'relationships' holds links to others.
// 'id' and 'type' MUST NOT appear inside attributes.

관계

관계는 리소스 식별자 객체({type, id})로 리소스를 다른 것들과 연결합니다. to-one 관계는 단일 식별자를, to-many는 배열을 씁니다. 'links' 객체가 내비게이션을 위해 'self'(관계 URL)와 'related'(관련 리소스 URL)를 제공합니다.

json
{
  "data": {
    "type": "articles",
    "id": "1",
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "9" },
        "links": {
          "self": "/articles/1/relationships/author",
          "related": "/articles/1/author"
        }
      },
      "tags": {
        "data": [
          { "type": "tags", "id": "1" },
          { "type": "tags", "id": "2" }
        ]
      }
    }
  }
}

// to-one: data is a single resource identifier.
// to-many: data is an array of resource identifiers.

Meta & Links

'meta'가 총 개수, 레이트 리밋, 경고 같은 비표준 정보를 운반합니다. 'links'가 하이퍼미디어 내비게이션을 제공합니다: 페이징용 self, first, prev, next, last, 그리고 관련 URL. 없는 링크(예: 첫 페이지의 prev)에는 null을 쓰세요.

json
{
  "meta": {
    "totalPages": 5,
    "currentPage": 1,
    "rateLimit": 100
  },
  "links": {
    "self": "/articles?page=1",
    "first": "/articles?page=1",
    "prev": null,
    "next": "/articles?page=2",
    "last": "/articles?page=5"
  },
  "data": [ /* ... */ ]
}

// meta: non-standard metadata (counts, rate limits, etc.).
// links: pagination and resource URLs.

오류

JSON:API 오류 문서는 최상위 'errors' 배열을 갖습니다('data'는 없음). 각 오류 객체에는 선택적 필드가 있습니다: id, status(문자열인 HTTP 코드), code(앱별), title(짧은 요약), detail(사람용 설명), source(JSON Pointer로 나쁜 필드를 가리킴), meta.

json
{
  "errors": [
    {
      "id": "err-123",
      "status": "404",
      "code": "NOT_FOUND",
      "title": "Resource Not Found",
      "detail": "Article 99 does not exist.",
      "source": { "pointer": "/data/attributes/id" },
      "meta": { "requestId": "abc-9" }
    }
  ]
}

// Errors is an array of error objects.
// status: HTTP status string; code: app-specific code.
// source.pointer: JSON Pointer to the offending field.
17

JSON5

JSON5 기능

JSON5는 사람이 쓰는 설정을 위해 설계된 JSON 상위집합입니다. 주석, 따옴표 없는/작은따옴표 문자열, 끝 쉼표, 16진수/Infinity/NaN 숫자, 느슨한 숫자 형식을 추가합니다. JSON5는 표준 JSON이 아닙니다 — 교환용으로는 JSON5 파서(json5 npm 패키지)를 쓰고 JSON으로 변환하세요.

json
// JSON5 is a superset of JSON with friendlier syntax.
{
  // line comments
  /* block comments */
  unquotedKey: "ok",            // unquoted keys
  "with space": "ok",            // quoted keys still allowed
  singleQuote: 'single',        // single-quoted strings
  trailing: [1, 2, 3,],         // trailing commas
  hex: 0x1F,                     // hexadecimal numbers
  inf: Infinity,                 // Infinity, -Infinity, NaN
  leadingDot: .5,                // leading decimal point
  trailingDot: 5.,               // trailing decimal point
  plus: +5,                      // leading plus
}

// JSON5 is NOT standard JSON—use a JSON5 parser.

주석

JSON5는 // 한 줄 주석과 /* */ 블록 주석을 모두 지원합니다. 표준 JSON은 이를 금지합니다. 이로써 JSON5가 사람이 쓰는 설정 파일에 이상적입니다. VS Code의 settings.json과 TypeScript의 tsconfig.json은 JSONC(주석이 있는 JSON)를 쓰며 — 비슷하지만 약간 다른 부분집합입니다.

json
{
  // Single-line comment (like JS)
  "name": "Alice",

  /* Block comment
     spanning multiple lines */
  "age": 30,

  "active": true // end-of-line comment
}

// Standard JSON rejects comments.
// JSON5 supports // and /* */ comments everywhere.
// VS Code's settings.json and tsconfig.json use JSONC (a subset).

끝 쉼표

JSON5는 객체와 배열의 마지막 요소 뒤 끝 쉼표를 허용합니다. 표준 JSON은 이를 거부합니다. 끝 쉼표는 필드를 추가하거나 재정렬할 때 diff 노이즈를 줄입니다(각 줄이 쉼표로 끝날 수 있음). 많은 현대 언어와 설정 형식이 이제 이를 허용합니다.

json
{
  "a": 1,
  "b": 2,
  "c": 3,           // <-- trailing comma OK in JSON5
}

// Arrays too:
[1, 2, 3,]

// Standard JSON rejects trailing commas.
// JSON5 allows them, reducing diff noise when adding fields.

따옴표 없는 & 작은따옴표 문자열

JSON5는 따옴표 없는 식별자 키([A-Za-z_$][A-Za-z0-9_$]*와 매칭)와 작은따옴표/큰따옴표 문자열을 모두 허용합니다. 작은따옴표 문자열 안에서는 '을 \'로, 큰따옴표 안에서는 "을 \"로 이스케이프하세요. 가독성을 위해 JavaScript 객체 리터럴 문법을 미러링합니다.

json
{
  unquoted: "value",          // unquoted identifier key
  "quoted key": "value",       // quoted key (for special chars)
  single: 'single-quoted',     // single-quoted string value
  mixed: 'it\'s ok',           // escape single quote inside
  double: "she said \"hi\"",  // escape double quote inside
}

// Unquoted keys must be valid identifiers ([A-Za-z_$][A-Za-z0-9_$]*).
// Single and double quotes are both allowed for strings.

숫자 & 문자열 (확장)

JSON5는 숫자를 확장합니다: 16진수(0xFF), 선행/후행 소수점(.5, 5.), 선행 플러스(+5), 키워드 Infinity, -Infinity, NaN. 이들은 모두 표준 JSON에서 거부됩니다. JSON5 문자열은 여전히 개행에 이스케이프 시퀀스(\n)를 씁니다 — 맨 여러 줄 문자열은 없습니다.

json
{
  hex: 0xFF,                    // hexadecimal
  leadingDot: .5,               // .5 instead of 0.5
  trailingDot: 5.,              // 5. instead of 5.0
  leadingPlus: +5,              // +5 (standard JSON rejects +)
  infinity: Infinity,           // Infinity (not in standard JSON)
  negativeInfinity: -Infinity,
  nan: NaN,
  multiline: 'line1\nline2'    // escape sequences like JSON
}

// JSON5 does NOT support real multi-line strings or bareword NaN.
18

JSON Lines (JSONL)

JSONL 형식

JSON Lines(JSONL 또는 NDJSON)는 각 줄이 별개의 완전한 JSON 값인 형식입니다. 감싸는 배열이 없습니다. 이로써 스트리밍, 로그, 큰 데이터셋에 이상적입니다: 전체 파일을 로드하지 않고 줄 단위로 처리할 수 있습니다. 확장자: .jsonl, .ndjson.

json
// A JSON Lines file (.jsonl / .ndjson) is one JSON value per line:

{"name": "Alice", "age": 30}
{"name": "Bob", "age": 25}
{"name": "Carol", "age": 35}

// Rules:
//   - Each line is a COMPLETE, valid JSON value.
//   - Lines are separated by newlines (\n).
//   - No enclosing [ ] array.
//   - Each line is parsed independently.

JSONL 읽기

줄을 순회하며 각각을 JSON.parse/loads로 파싱해 JSONL을 읽으세요. 상수 메모리로 파일을 스트리밍합니다 — 거대한 데이터셋에 이상적입니다. 빈 줄은 건너뛰세요. Node.js에서는 파일 스트림 위의 readline을, Python에서는 파일 객체를 직접 순회하세요. 전체 파일을 로드할 필요가 없습니다.

json
// JavaScript (Node.js) — line by line:
const fs = require("fs");
const readline = require("readline");

const rl = readline.createInterface({
  input: fs.createReadStream("data.jsonl"),
  crlfDelay: Infinity,
});

for await (const line of rl) {
  if (!line.trim()) continue;
  const obj = JSON.parse(line);
  console.log(obj.name);
}

// Python:
//   import json
//   with open("data.jsonl") as f:
//       for line in f:
//           obj = json.loads(line)

JSONL 쓰기

JSONL 쓰기는 각 레코드를 JSON.stringify/dumps로(컴팩트, 들여쓰기 없음) 직렬화하고 개행을 덧붙입니다. 효율을 위해 쓰기 가능한 스트림(Node)이나 쓰기 모드로 연 파일(Python)을 쓰세요. 컴팩트 형식이 줄을 짧고 파싱 가능하게 유지합니다; 한 줄에 한 레코드가 규칙입니다.

json
// JavaScript (Node.js):
const fs = require("fs");
const out = fs.createWriteStream("out.jsonl");
for (const obj of records) {
  out.write(JSON.stringify(obj) + "\n");
}
out.end();

// Python:
//   import json
//   with open("out.jsonl", "w") as f:
//       for obj in records:
//           f.write(json.dumps(obj) + "\n")

// One JSON per line; compact form (no indent) is conventional.

활용 사례

JSONL은 로그 파일, 큰 데이터셋, ML 학습 데이터, DB 덤프, append 전용 이벤트 스트림에서 빛을 발합니다. 각 줄이 독립적이라 재작성 없이 append하고, 손상된 줄 뒤에서 파싱을 재개하고, 병렬 처리할 수 있습니다. jq와 셸 파이프 같은 도구가 자연스럽게 어울립니다.

json
// JSONL is ideal for:
//   - log files (one event per line)
//   - large datasets (streaming, append-only)
//   - machine learning training data
//   - database exports/imports
//   - append-only event streams

// Example: log entry per line
{"ts": "2024-01-15T10:00:00Z", "level": "info", "msg": "started"}
{"ts": "2024-01-15T10:00:01Z", "level": "error", "msg": "failed"}

// Tools: jq, xargs, awk | json.loads — all work line-by-line.

JSONL vs JSON 배열

JSON 배열은 레코드를 [ ]로 감싸 파싱에 전체 파일의 로딩(또는 신중한 스트리밍)이 필요합니다. JSONL은 줄마다 한 레코드를 두어 진짜 스트리밍, 쉬운 append, 손상된 줄로부터의 복구를 가능하게 합니다. 크거나 계속 자라는 데이터셋에는 JSONL이 거의 항상 더 나은 선택입니다.

json
// JSON Array (one big file):
[
  {"name": "Alice"},
  {"name": "Bob"},
  {"name": "Carol"}
]

// JSONL (one per line):
{"name": "Alice"}
{"name": "Bob"}
{"name": "Carol"}

// JSON Array: must load whole file to parse; hard to append.
// JSONL: streamable, appendable, resumable; slightly more
//        per-record overhead but far better for big files.
19

보안

JSONP 위험

JSONP는 <script> 태그가 동일 출처 정책을 우회해 교차 출처 데이터를 가져올 수 있게 JSON을 JavaScript 콜백으로 감쌉니다. 위험합니다: 어떤 사이트든 응답을 읽을 수 있고, 콜백 주입이 XSS를 가능하게 하며, 요청이 피해자의 쿠키를 운반합니다. 대신 CORS를 쓰세요 — JSONP는 레거시이며 안전하지 않습니다.

json
// JSONP (JSON with Padding) bypasses same-origin policy
// by wrapping JSON in a script callback:
callbackHandler({"secret": "data"});

// Loaded via <script src="https://api.example.com/data?callback=callbackHandler">

// RISKS:
//   - Any site can include the URL and read the response.
//   - XSS if the callback name is attacker-controlled.
//   - CSRF: the request is made with the victim's cookies.

// MODERN ALTERNATIVE: use CORS instead of JSONP.
// JSONP is legacy—avoid it for new APIs.

XSS 방지

HTML <script> 태그에 삽입된 JSON이 XSS를 일으킬 수 있습니다: 문자열 '</script>'가 스크립트를 조기 종료합니다. 또한 U+2028과 U+2029(줄/문단 구분자)는 JSON 문자열에서 유효하지만 JavaScript를 깨뜨립니다. HTML에 JSON을 넣을 때 <, >, &, U+2028, U+2029를 이스케이프하거나 serialize-javascript 같은 라이브러리를 쓰세요.

json
// JSON itself is data, not executable—BUT embedding it in
// HTML can cause XSS if not careful.

// BAD: output JSON inside <script> without escaping:
//   <script>
//     var data = {"name": "</script><script>alert(1)</script>"};
//   </script>

// GOOD: escape < and > (and &) when embedding in HTML:
const safe = JSON.stringify(data)
  .replace(/</g, "\\u003c")
  .replace(/>/g, "\\u003e")
  .replace(/&/g, "\\u0026")
  .replace(/\u2028/g, "\\u2028")
  .replace(/\u2029/g, "\\u2029");

// Or use a library: js-xss, serialize-javascript.

프로토타입 오염

프로토타입 오염은 '__proto__'나 'constructor' 같은 키를 담은 신뢰할 수 없는 JSON이 객체로 병합될 때 일어나며, Object.prototype을 오염시켜 모든 객체에 영향을 줍니다. 방어: Object.create(null) 사용, 위험한 키 차단, 신뢰할 수 없는 데이터에는 Map 선호, 병합 라이브러리 최신 유지.

json
// Merging untrusted JSON into objects can pollute prototypes:
const evil = JSON.parse('{"__proto__": {"isAdmin": true}}');

// BAD merge (Object.assign does NOT pollute, but some libs do):
//   function merge(target, src) {
//     for (const k in src) target[k] = src[k];
//   }

// Attackers can set Object.prototype.isAdmin = true,
// affecting ALL objects.

// Defenses:
//   - Use Object.create(null) for parsed objects.
//   - Block keys like __proto__, constructor, prototype.
//   - Use Map instead of plain objects for untrusted data.
//   - Keep dependencies updated (some had merge() flaws).

JSON을 통한 주입

JSON 자체는 주입에 강하지만 문자열 연결로 만드는 것은 위험합니다 — 사용자 입력이 JSON 구조를 탈출할 수 있습니다. 항상 진짜 직렬화기(JSON.stringify)를 쓰세요. 하류도 마찬가지입니다: 파라미터화된 SQL 쿼리, 인수 배열이 있는 execFile, HTML 이스케이프 템플리팅 엔진을 쓰세요.

json
// JSON itself is not injectable, but building JSON by
// concatenation is dangerous:

// BAD: string concatenation
//   const json = '{"name": "' + userInput + '"}';
//   // userInput = '"); drop table; //'  ->  breaks out

// GOOD: always use a real serializer
const json = JSON.stringify({ name: userInput });

// For SQL: use parameterized queries, not JSON interpolation.
// For shell: use execFile with arg arrays, not string concat.
// For HTML: use textContent or a templating engine that escapes.

크거나 깊은 JSON으로 인한 DoS

JSON 기반 DoS: 거대한 파일이 RAM을 고갈시키고, 깊은 중첩이 파서 스택을 오버플로우시키며, 병적 구조('billion laughs'의 JSON판)가 작은 입력을 부풀립니다. 방어: 프록시에서 요청 본문 크기 상한, 파싱 깊이 제한, 큰 입력에 스트리밍 파서, 타임아웃 설정.

json
// Attackers can craft JSON to exhaust memory or CPU:
//
//   1. Huge file: 1 GB of '[1,1,1,...]' to exhaust RAM.
//   2. Deep nesting: '{"a":{"a":{"a":...}}}' (10000 levels)
//      to overflow the parser's stack.
//   3. 'Billion laughs': nested entity expansion (XML-era,
//      but JSON analogs exist with $ref in some libs).
//   4. Many keys: 10 million keys in one object.

// Defenses:
//   - Cap request body size at the server/reverse proxy.
//   - Limit parsing depth (Ajv, fast-json-parse options).
//   - Use streaming parsers (stream-json, oboe) for big input.
//   - Set timeouts on parsing.

안전한 파싱 실천

안전한 JSON 파싱: 항상 JSON.parse를 쓰고(eval 금지), 사용 전에 스키마로 검증하고(Ajv, jsonschema), 깊이와 키 수에 상한을 두고, __proto__ 키를 비활성화하며, 신뢰할 수 없는 입력은 Web Worker나 샌드박스에서 파싱을 고려하세요. JSON.parse 자체는 코드 실행으로부터 안전합니다; 위험은 파싱된 데이터의 사용 방법에 있습니다.

json
// 1. Validate with a schema before using untrusted JSON.
const Ajv = require("ajv");
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);
if (!validate(data)) throw new Error(ajv.errorsText(validate.errors));

// 2. Limit depth and key count when parsing.
// 3. Use reviver/replacer to coerce types safely.
// 4. Never eval() or Function('return ' + json) — use JSON.parse.
// 5. Disable dangerous features (e.g., __proto__ keys).
// 6. Parse untrusted JSON in a sandbox or worker if possible.

// JSON.parse is safe; eval is NOT.
20

모범 사례 & 도구

스키마 우선

API를 스키마 우선으로 설계하세요: JSON Schema를 정의하고, 이로부터 언어 타입을 생성하고(typescript-json-schema, quicktype, jsonschema2pojo), 런타임에 요청/응답을 검증합니다. 이는 계약 위반을 조기에 잡고, 코드 생성을 가능하게 하며, 살아있는 문서가 됩니다.

json
// Define a JSON Schema before shipping an API.
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "name"],
  "properties": {
    "id":   { "type": "integer" },
    "name": { "type": "string", "minLength": 1, "maxLength": 100 }
  },
  "additionalProperties": false
}

// Generate types from the schema (TypeScript, Java, Go, ...).
// Validate both requests and responses against the schema.
// Publish the schema for clients (OpenAPI, JSON Schema).

일관된 네이밍

키의 네이밍 관례를 하나 정해 일관되게 적용하세요: camelCase(대부분의 JSON API와 JS), snake_case(Python/Ruby 백엔드, Google API), PascalCase(.NET). 스타일을 섞으면 혼란스럽습니다. 프런트와 백엔드가 다르면 스키마 안에서 섞지 말고 단일 경계에서 변환하세요.

json
// Pick ONE naming convention and apply it everywhere.

// camelCase (most JSON APIs, JavaScript ecosystem):
{ "firstName": "Alice", "lastName": "Smith" }

// snake_case (Python/Ruby backends, many Google APIs):
{ "first_name": "Alice", "last_name": "Smith" }

// kebab-case (rare in JSON, common in URLs/config):
{ "first-name": "Alice" }

// PascalCase (rare in JSON keys, common in C#/.NET types):
{ "FirstName": "Alice" }

// Avoid mixing; convert at the boundary if the front/back differ.

버저닝

첫날부터 API에 버전을 두세요: URL 경로(/v1/), 페이로드의 버전 필드, Accept 헤더(미디어 타입), 또는 네임스페이스(JSON-LD @context). 추가적 변경(새 선택 필드)은 보통 파괴적이지 않습니다; 제거/이름 변경된 필드나 바뀐 의미에는 버전을 올리세요.

json
// 1. Version in the URL path:
//    https://api.example.com/v1/users

// 2. Version field in the payload:
{ "version": "1.0", "data": { ... } }

// 3. Accept header / media type:
//    Accept: application/vnd.example.v1+json

// 4. Namespace the JSON (JSON-LD, JSON:API 'type'):
{ "@context": "https://schema.org/v1", ... }

// Plan for evolution: add optional fields freely, but bump
// the version for breaking changes (removed/renamed fields,
// changed semantics or types).

인코딩 (UTF-8)

UTF-8이 JSON의 기본이자 널리 권장되는 유일한 인코딩입니다. 파일은 BOM 없이 UTF-8로 저장하고(일부 파서가 오동작), Content-Type에 charset=utf-8을 설정하고, Content-Length는 바이트 단위로 설정하세요. Python에서는 \uXXXX 이스케이프 대신 유니코드 문자를 읽기 쉽게 유지하려 ensure_ascii=False를 전달하세요.

json
// Always use UTF-8 for JSON.
//   - Save files as UTF-8 (no BOM).
//   - Set Content-Type: application/json; charset=utf-8.
//   - Set Content-Length in bytes (not characters).

// In Node.js:
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(data));

// In Python:
import json
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False)

// ensure_ascii=False keeps Unicode readable in the file.

성능 팁

성능을 위해: 버퍼링 대신 큰 JSON을 스트리밍하고(ijson, stream-json, Jackson streaming), 빠른 직렬화기를 쓰고(orjson, fast-json-stringify), 컴팩트로 전송하고 HTTP 위에서 gzip/brotli로 압축하며, 깊은 중첩과 거대한 배열을 피하고, 재파싱을 피하려 파싱 결과를 캐시하세요.

json
// 1. Stream large JSON instead of buffering it all.
//    - Node: stream-json, JSONStream
//    - Python: ijson
//    - Java: Jackson streaming API

// 2. Use a fast serializer:
//    - Node: fast-json-stringify (schema-based), orjson (Python)
//    - Compile serializers from a schema for hot paths.

// 3. Compact JSON for transmission; pretty only for humans.

// 4. Avoid deep nesting and huge arrays when possible.

// 5. Compress with gzip/brotli over HTTP (huge savings).

// 6. Cache parsed results; don't re-parse the same payload.

도구 & 검증기

JSON 작업용 도구: 온라인 검증기(jsonlint.com, jsonschemavalidator.net), CLI 도구(조회/포맷용 jq, 검증용 jsonschema), 에디터 지원(VS Code와 JetBrains에 JSON + 스키마 검증 내장), 코드 생성기(quicktype이 JSON이나 스키마에서 TypeScript/Java/Go 등의 타입을 생성).

json
// Online validators:
//   - https://jsonlint.com
//   - https://jsonformatter.org
//   - https://www.jsonschemavalidator.net

// CLI tools:
//   - jq          (filter, query, format JSON on the command line)
//   - jaq         (Rust jq clone, faster)
//   - jsonschema  (Python CLI for schema validation)
//   - ajv         (Node CLI/library for JSON Schema)

// Editor support:
//   - VS Code: built-in JSON + schema validation
//   - JetBrains: built-in JSON + schema support
//   - vim/emacs: plugins available

// Schema tools:
//   - quicktype   (generate types from JSON)
//   - typescript-json-schema
//   - jsonschema2pojo (Java)

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.