DevToolBox무료
블로그

JSON 포매터 & 검증기: 온라인 포맷, 검증 완전 가이드

12분 읽기by DevToolBox

JSON 포맷터JSON 유효성 검사기 도구는 API, 설정 파일, 데이터 교환을 다루는 모든 개발자에게 필수적입니다. 가독성을 위한 JSON 포맷팅, 구문 오류를 잡기 위한 온라인 JSON 검증, 디버깅을 위한 JSON 미화 출력이 필요하든, 이 포괄적인 가이드가 모든 것을 다룹니다. 무료 온라인 JSON 포맷터 도구는 브라우저에서 포맷팅, 유효성 검사, 축소, 구문 오류 감지를 즉시 처리합니다.

무료 JSON 포맷팅 및 유효성 검사 도구를 사용해 보세요.

JSON이란?

JSON(JavaScript Object Notation)은 사람이 읽고 쓰기 쉽고 기계가 파싱하고 생성하기 쉬운 경량의 텍스트 기반 데이터 교환 형식입니다. 웹 API, 설정 파일, NoSQL 데이터베이스에서 데이터 교환의 사실상 표준이 되었습니다.

JSON 문서는 두 가지 주요 구조로 구성됩니다: 객체(중괄호 {}로 감싸진 키-값 쌍의 컬렉션)와 배열(대괄호 []로 감싸진 값의 순서 목록). 값은 문자열, 숫자, 불리언, null, 객체, 배열이 될 수 있습니다.

JSON은 RFC 8259ECMA-404로 정의됩니다. 미디어 타입은 application/json이고 파일 확장자는 .json입니다. XML과 달리 JSON은 주석, 네임스페이스, 속성을 지원하지 않습니다.

JSON 포맷터가 필요한 이유

가독성: API의 원시 JSON은 공백 없는 긴 한 줄인 경우가 많습니다. JSON 포맷터는 들여쓰기와 줄 바꿈을 추가합니다.

디버깅: JSON 유효성 검사기는 구문 오류의 정확한 위치를 몇 초 만에 식별합니다.

유효성 검사: 배포 전에 항상 JSON을 검증하여 사일런트 실패와 프로덕션 문제를 방지하세요.

축소: JSON 축소는 불필요한 공백을 제거하여 페이로드 크기를 줄이고 API 응답을 가속화합니다.

일반적인 JSON 구문 오류

JSON 구문 오류는 전체 애플리케이션을 중단시킬 수 있습니다. 가장 흔한 실수들:

후행 쉼표: JSON은 마지막 항목 뒤에 쉼표를 허용하지 않습니다. {"a": 1, "b": 2,}는 유효하지 않습니다.

// INVALID: trailing comma
{
  "name": "John",
  "age": 30,
}

// VALID: no trailing comma
{
  "name": "John",
  "age": 30
}

작은따옴표: JSON은 모든 문자열과 키에 큰따옴표를 요구합니다. {'name': 'John'}은 유효하지 않습니다.

// INVALID: single quotes
{'name': 'John', 'age': 30}

// VALID: double quotes
{"name": "John", "age": 30}

따옴표 없는 키: 모든 키는 큰따옴표로 감싸진 문자열이어야 합니다.

주석: 표준 JSON은 주석을 지원하지 않습니다. JSONC, YAML, TOML을 사용하세요.

// INVALID: comments not allowed in JSON
{
  "name": "John", // this is a comment
  "age": 30       /* block comment */
}

// VALID: no comments
{
  "name": "John",
  "age": 30
}

undefined나 NaN: JSON은 null만 지원하며, undefined, NaN, Infinity는 지원하지 않습니다.

// INVALID in JSON (JavaScript-specific values)
{
  "value1": undefined,
  "value2": NaN,
  "value3": Infinity
}

// VALID: use null instead
{
  "value1": null,
  "value2": null,
  "value3": null
}

괄호 불일치: 모든 {[에는 대응하는 닫는 괄호가 필요합니다.

잘못된 이스케이프 시퀀스: JSON은 특정 이스케이프 시퀀스를 지원: \", \\, \n, \r, \t, \uXXXX.

JSON 포맷팅 방법

워크플로우에 따른 다양한 JSON 포맷팅 방법:

온라인 JSON 포맷터: 무료 도구에 데이터를 붙여넣어 즉시 포맷팅과 유효성 검사를 수행합니다.

커맨드라인 jq: jq는 가장 강력한 커맨드라인 JSON 프로세서입니다.

Python 내장 모듈: python -m json.tool file.json으로 터미널에서 직접 포맷팅.

IDE 확장: VS Code는 내장 JSON 포맷팅(Shift+Alt+F)을 제공. JetBrains는 Ctrl+Alt+L.

브라우저 DevTools: DevTools는 네트워크 탭에서 JSON 응답을 자동 포맷팅합니다.

JSON 유효성 검사 규칙

JSON을 올바르게 검증하기 위한 RFC 8259 규칙:

데이터 타입: JSON은 6가지 타입 지원: string, number, boolean, null, object, array.

// All six JSON data types demonstrated:
{
  "string": "Hello World",
  "number": 42.5,
  "boolean": true,
  "nullValue": null,
  "object": {
    "nested": "value"
  },
  "array": [1, "two", false, null, {"key": "val"}, [1,2,3]]
}

문자열: 큰따옴표로 감싸야 하며 특정 이스케이프 시퀀스 사용.

숫자: 정수 또는 부동소수점, 과학적 표기법 허용, 선행 제로/NaN/Infinity 불가.

// Valid JSON numbers:
42          // integer
-17         // negative integer
3.14        // floating point
2.5e10      // scientific notation
-1.23e-4    // negative scientific notation

// INVALID JSON numbers:
01          // leading zero not allowed
.5          // must have digit before decimal
+1          // leading plus not allowed
0xFF        // hex not allowed
0o77        // octal not allowed
NaN         // not a valid JSON value
Infinity    // not a valid JSON value

객체: 키는 고유한 문자열. 빈 객체 {} 유효.

배열: 혼합 타입 허용. 빈 배열 [] 유효. 임의 깊이 중첩.

인코딩: UTF-8이 기본이며 가장 널리 사용.

최상위 값: RFC 8259는 최상위에 모든 JSON 값을 허용.

코드 예제: JSON 포맷팅 및 유효성 검사

JavaScript: JSON 포맷팅 및 유효성 검사

JavaScript는 JSON.parse()JSON.stringify()로 유효성 검사와 포맷팅을 제공:

// ===== JSON.parse(): Validate JSON =====

// Valid JSON string
const jsonString = '{"name": "Alice", "age": 30, "active": true}';
const data = JSON.parse(jsonString);
console.log(data.name); // "Alice"

// Validate JSON safely with try/catch
function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    console.error('JSON syntax error:', e.message);
    return false;
  }
}

isValidJSON('{"valid": true}');     // true
isValidJSON('{invalid: true}');     // false — "Unexpected token i"
isValidJSON('{"trailing": 1,}');    // false — "Unexpected token }"

// ===== JSON.stringify(): Format / Pretty Print JSON =====

const obj = {
  name: "Alice",
  age: 30,
  address: {
    city: "New York",
    zip: "10001"
  },
  hobbies: ["reading", "coding", "hiking"]
};

// Pretty print with 2-space indentation
const formatted = JSON.stringify(obj, null, 2);
console.log(formatted);
/*
{
  "name": "Alice",
  "age": 30,
  "address": {
    "city": "New York",
    "zip": "10001"
  },
  "hobbies": [
    "reading",
    "coding",
    "hiking"
  ]
}
*/

// Pretty print with 4-space indentation
console.log(JSON.stringify(obj, null, 4));

// Pretty print with tab indentation
console.log(JSON.stringify(obj, null, "\t"));

// Minify JSON (no whitespace)
const minified = JSON.stringify(obj);
// {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}

// Custom replacer: filter specific keys
const filtered = JSON.stringify(obj, ["name", "age"], 2);
/*
{
  "name": "Alice",
  "age": 30
}
*/

// Reviver function: transform values during parsing
const parsed = JSON.parse('{"date": "2025-01-15T00:00:00Z"}', (key, value) => {
  if (key === 'date') return new Date(value);
  return value;
});
console.log(parsed.date instanceof Date); // true

Python: JSON 포맷팅 및 유효성 검사

Python json 모듈은 json.dumps()indent 매개변수로 포맷팅:

import json

# ===== json.loads(): Validate JSON =====

json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"])  # "Alice"

# Validate JSON safely
def is_valid_json(s):
    try:
        json.loads(s)
        return True
    except json.JSONDecodeError as e:
        print(f"JSON syntax error at line {e.lineno}, col {e.colno}: {e.msg}")
        return False

is_valid_json('{"valid": true}')      # True
is_valid_json('{invalid: true}')      # False
is_valid_json('{"trailing": 1,}')     # False

# ===== json.dumps(): Format / Pretty Print JSON =====

data = {
    "name": "Alice",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    },
    "hobbies": ["reading", "coding", "hiking"]
}

# Pretty print with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)

# Pretty print with sorted keys
formatted_sorted = json.dumps(data, indent=2, sort_keys=True)
print(formatted_sorted)

# Minify JSON (compact output)
minified = json.dumps(data, separators=(",", ":"))
print(minified)
# {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}

# Handle non-ASCII characters (useful for i18n)
data_intl = {"city": "Tokyo", "greeting": "Hello"}
print(json.dumps(data_intl, ensure_ascii=False, indent=2))

# Read and format a JSON file
with open("data.json", "r") as f:
    data = json.load(f)

with open("data_formatted.json", "w") as f:
    json.dump(data, f, indent=2)

# Command line: python -m json.tool
# $ echo '{"a":1,"b":2}' | python -m json.tool
# {
#     "a": 1,
#     "b": 2
# }

커맨드라인: jq, python, node

커맨드라인에서 JSON을 포맷팅하고 유효성을 검사하는 다양한 도구:

# ===== jq: The Swiss Army knife for JSON =====

# Pretty print JSON
echo '{"name":"Alice","age":30}' | jq .
# {
#   "name": "Alice",
#   "age": 30
# }

# Minify JSON (compact output)
echo '{
  "name": "Alice",
  "age": 30
}' | jq -c .
# {"name":"Alice","age":30}

# Extract specific fields
echo '{"name":"Alice","age":30,"city":"NYC"}' | jq '{name, city}'
# {"name": "Alice", "city": "NYC"}

# Format a JSON file
jq . input.json > formatted.json

# Validate JSON (exit code 0 = valid, non-zero = invalid)
echo '{"valid": true}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"
echo '{invalid}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"

# Sort keys
echo '{"b":2,"a":1,"c":3}' | jq -S .
# {"a": 1, "b": 2, "c": 3}

# ===== python -m json.tool =====

# Format JSON from stdin
echo '{"a":1,"b":2}' | python3 -m json.tool

# Format a JSON file
python3 -m json.tool input.json output.json

# Sort keys
echo '{"b":2,"a":1}' | python3 -m json.tool --sort-keys

# ===== Node.js one-liner =====

# Pretty print JSON
echo '{"a":1,"b":2}' | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))"

# Simpler: use node -p
node -p "JSON.stringify({a:1,b:[2,3]}, null, 2)"

curl + jq 파이프라인

API에서 JSON을 가져와 curl에서 jq로 파이프하여 포맷팅하는 일반적인 워크플로우:

# Fetch and format JSON from a REST API
curl -s https://api.github.com/users/octocat | jq .

# Fetch, extract specific fields, and format
curl -s https://api.github.com/users/octocat | jq '{login, name, bio, public_repos}'

# Fetch and validate (check exit code)
curl -s https://api.example.com/data | jq . > /dev/null 2>&1
if [ $? -eq 0 ]; then
  echo "Response is valid JSON"
else
  echo "Response is NOT valid JSON"
fi

# POST JSON and format the response
curl -s -X POST https://api.example.com/data \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","age":30}' | jq .

# Save formatted JSON to file
curl -s https://api.github.com/users/octocat | jq . > user.json

# Minify before sending (reduce payload size)
DATA=$(jq -c . large-payload.json)
curl -s -X POST https://api.example.com/data \
  -H "Content-Type: application/json" \
  -d "$DATA" | jq .

JSON 모범 사례

깔끔하고 고성능 JSON을 작성하기 위한 모범 사례:

키에 camelCase 사용: 대부분의 JSON API는 camelCase를 사용합니다. 일관성을 유지하세요.

// camelCase (recommended for most APIs)
{
  "firstName": "Alice",
  "lastName": "Smith",
  "phoneNumber": "+1-555-0123",
  "isActive": true
}

// snake_case (common in Python/Ruby ecosystems)
{
  "first_name": "Alice",
  "last_name": "Smith",
  "phone_number": "+1-555-0123",
  "is_active": true
}

중첩을 얕게 유지: 깊은 중첩(3-4레벨 이상)은 읽기 어렵습니다. 플래트닝을 고려하세요.

// BAD: deeply nested (hard to read and parse)
{
  "company": {
    "departments": {
      "engineering": {
        "teams": {
          "frontend": {
            "members": [{"name": "Alice"}]
          }
        }
      }
    }
  }
}

// BETTER: flattened structure
{
  "companyId": "acme",
  "departmentId": "engineering",
  "teamId": "frontend",
  "members": [{"name": "Alice"}]
}

큰 파일 주의: 수 MB 이상의 JSON 파일에는 스트리밍 파서를 사용하세요.

JSON Schema로 검증: 프로덕션에서는 ajvjsonschema로 JSON Schema 검증.

// JSON Schema example for validating user objects
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" },
    "roles": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1
    }
  },
  "required": ["name", "email"]
}

바이너리 데이터 피하기: JSON은 텍스트 형식. 바이너리에는 Base64나 URL을 사용.

일관된 null 처리: null 키를 생략할지 명시적으로 포함할지 결정하고 일관되게 적용.

JSON vs 대안: YAML, TOML, XML

JSON만이 유일한 직렬화 형식은 아닙니다. 주요 대안과의 비교:

FeatureJSONYAMLTOMLXML
ReadabilityGoodExcellentExcellentModerate
CommentsNoYesYesYes
Data types6 typesRich (dates, etc.)Rich (dates, etc.)Text only
NestingUnlimitedUnlimitedLimitedUnlimited
Multi-line stringsNoYesYesYes (CDATA)
Parser supportUniversalWideGrowingUniversal
File sizeSmallSmallerSmallestLarge (verbose)
Best forAPIs, dataConfig filesSimple configDocuments, SOAP

API에는 JSON, 편집 가능한 설정에는 YAML, 간단한 설정에는 TOML, 기존 표준(SOAP, RSS)에는 XML을 선택.

자주 묻는 질문

온라인에서 JSON을 포맷팅하려면?

원시 JSON을 당사 도구 같은 포맷터에 붙여넣으세요. 도구가 자동으로 구문을 검증하고 들여쓰기를 추가하며 오류를 하이라이트합니다. 2칸 또는 4칸 들여쓰기 선택 가능. 도구는 브라우저에서 완전히 실행됩니다.

일반적인 JSON 구문 오류는?

가장 흔한 것들: 후행 쉼표, 작은따옴표, 따옴표 없는 키, 주석, undefined/NaN 값, 괄호 불일치, 잘못된 이스케이프 시퀀스.

JSON과 YAML의 차이점은?

JSON은 중괄호와 큰따옴표를 사용하고, YAML은 들여쓰기를 사용합니다. YAML은 주석과 여러 줄 문자열을 지원합니다. JSON은 기계 간 데이터 교환에 적합하고, YAML은 설정 파일에 적합합니다. JSON은 YAML의 엄격한 하위 집합입니다.

JSON 포맷팅과 유효성 검사 마스터는 현대 개발자에게 필수입니다. 무료 도구로 즉시 포맷팅과 유효성 검사를 수행하세요.

무료 온라인 도구로 JSON을 즉시 포맷팅, 유효성 검사, 축소하세요.

𝕏 Twitterin LinkedIn
도움이 되었나요?

최신 소식 받기

주간 개발 팁과 새 도구 알림을 받으세요.

스팸 없음. 언제든 구독 해지 가능.

Try These Related Tools

{ }JSON FormatterTSJSON to TypeScriptGoJSON to Go StructJSON Validator

Related Articles

JSON vs YAML vs TOML: 어떤 설정 포맷을 사용해야 할까?

JSON, YAML, TOML 설정 포맷을 비교합니다.

JSON Schema 유효성 검사: 타입, 도구, 모범 사례

JSON Schema 유효성 검사의 모든 것: 기본 타입부터 고급 패턴, 검증 라이브러리, TypeScript 및 API 통합까지.

JSON Parse Error: Unexpected Token — 찾고 고치는 방법

JSON 파싱 오류를 단계별로 해결하세요. unexpected token 오류의 원인, 문제 위치 찾기, 검증 도구.

JSON 포맷터 & 뷰티파이어: JSON 포맷팅 완전 가이드 (2026)

JSON을 온라인, VS Code, 커맨드라인, JavaScript/Python에서 포맷하고 뷰티파이하는 방법을 배우세요. 유효성 검사, 최소화, 뷰어, 일반적인 오류까지 다룹니다.