alltools.one
Development
2024-01-06
8 min
Development Team
jsonvalidationdebuggingerrorstroubleshooting

JSON 유효성 검사 오류: 완전한 문제 해결 가이드

JSON 유효성 검사 오류는 디버깅하기 frustrating하고 시간이 많이 소요될 수 있습니다. API 응답, 구성 파일 또는 데이터 교환을 다루는지 여부에 관계없이 일반적인 JSON 오류와 이를 수정하는 방법을 이해하는 것은 모든 개발자에게 필수적입니다.

일반적인 문제: 경험이 풍부한 개발자조차도 JSON 유효성 검사 오류를 디버깅하는 데 몇 시간을 보낼 수 있습니다. 이 가이드는 이를 빠르게 식별하고 수정하는 데 도움이 됩니다.

JSON 유효성 검사 이해

JSON 유효성 검사는 데이터 구조가 올바른 JSON 구문 및 형식화 규칙을 따르는지 확인합니다. 잘못된 JSON은 다음을 초래할 수 있습니다:

  • 애플리케이션에서의 파싱 실패
  • API 요청 거부
  • 구성 로딩 오류
  • 전송 중 데이터 손상
  • 프로덕션에서의 애플리케이션 충돌

가장 일반적인 JSON 유효성 검사 오류

1. 구문 오류

뒤따르는 쉼표

가장 빈번한 JSON 오류 중 하나:

// ❌ INVALID - Trailing comma
{
  "name": "John",
  "age": 30,
}

// ✅ VALID - No trailing comma
{
  "name": "John",
  "age": 30
}

누락된 따옴표

JSON은 모든 문자열 주위에 이중 따옴표가 필요합니다:

// ❌ INVALID - Unquoted keys and single quotes
{
  name: 'John',
  age: 30
}

// ✅ VALID - Double quotes required
{
  "name": "John",
  "age": 30
}

닫히지 않은 대괄호/중괄호

짝이 맞지 않는 대괄호는 파싱 실패를 초래합니다:

// ❌ INVALID - Missing closing brace
{
  "users": [
    {"name": "John"},
    {"name": "Jane"}
  
// ✅ VALID - Properly closed
{
  "users": [
    {"name": "John"},
    {"name": "Jane"}
  ]
}

2. 데이터 유형 오류

잘못된 값

JSON은 유효한 값에 대한 엄격한 규칙을 가집니다:

// ❌ INVALID - undefined, functions, comments
{
  "name": "John",
  "age": undefined,           // Use null instead
  "callback": function() {},  // Functions not allowed
  // "comment": "not allowed" // Comments not supported
}

// ✅ VALID - Proper JSON values
{
  "name": "John",
  "age": null,
  "isActive": true
}

숫자 형식 문제

JSON 숫자는 특정 형식 규칙을 따라야 합니다:

// ❌ INVALID - Various number format issues
{
  "decimal": .5,        // Must start with digit
  "hex": 0xFF,          // Hex not supported
  "octal": 0777,        // Octal not supported
  "infinity": Infinity  // Infinity not supported
}

// ✅ VALID - Proper number formats
{
  "decimal": 0.5,
  "integer": 255,
  "negative": -42,
  "scientific": 1.23e10
}

3. 구조 오류

중복 키

일부 파서는 중복 키를 허용하지만, 이는 유효하지 않은 JSON입니다:

// ❌ INVALID - Duplicate keys
{
  "name": "John",
  "age": 30,
  "name": "Jane"  // Duplicate key
}

// ✅ VALID - Unique keys
{
  "firstName": "John",
  "lastName": "Doe",
  "age": 30
}

부적절한 중첩

JSON은 중첩 깊이와 구조에 제한이 있습니다:

// ❌ PROBLEMATIC - Too deeply nested
{
  "level1": {
    "level2": {
      "level3": {
        "level4": {
          "level5": {
            // ... continues beyond practical limits
          }
        }
      }
    }
  }
}

// ✅ BETTER - Flatter structure
{
  "user": {
    "id": 123,
    "profile": {
      "name": "John",
      "preferences": ["dark-mode", "notifications"]
    }
  }
}

고급 유효성 검사 문제

문자 인코딩 문제

인코딩 문제: JSON은 UTF-8 인코딩이어야 합니다. 다른 인코딩은 유효성 검사 실패를 초래할 수 있습니다.

일반적인 인코딩 문제:

// ❌ PROBLEMATIC - Special characters
{
  "name": "José",           // May cause issues in some systems
  "emoji": "😀",           // Emoji can be problematic
  "currency": "€100"       // Currency symbols
}

// ✅ SAFER - Escaped Unicode
{
  "name": "Jos\u00e9",
  "emoji": "😀",
  "currency": "\u20ac100"
}

대형 데이터 유효성 검사

성능 고려사항:

{
  "metadata": {
    "size": "large",
    "validation": {
      "strategy": "streaming",
      "chunkSize": 1024,
      "timeout": 30000
    }
  },
  "data": {
    "note": "Large arrays should be validated in chunks"
  }
}

오류 메시지 및 디버깅

일반적인 파서 오류 메시지

1. "Unexpected token" 오류

오류: Unexpected token ',' at position 25 원인: 일반적으로 뒤따르는 쉼표 또는 잘못된 구두점 수정: 추가 쉼표, 세미콜론 또는 다른 구두점을 확인하세요

2. "Unexpected end of JSON input"

오류: Unexpected end of JSON input 원인: 불완전한 JSON 구조, 닫히지 않은 대괄호 수정: 모든 대괄호와 중괄호가 제대로 닫혔는지 확인하세요

3. "Invalid character" 오류

오류: Invalid character at position 15 원인: 제어 문자나 잘못된 따옴표 같은 잘못된 문자 수정: 보이지 않는 문자, 잘못된 따옴표 유형 확인

디버깅 전략

1. 줄 단위 유효성 검사

// JavaScript debugging approach
function validateJSONSteps(jsonString) {
  try {
    JSON.parse(jsonString);
    console.log("✅ Valid JSON");
  } catch (error) {
    console.error("❌ Invalid JSON:", error.message);
    
    // Find approximate error location
    const lines = jsonString.split('\n');
    const errorPosition = extractPosition(error.message);
    
    if (errorPosition) {
      console.log(`Error near position ${errorPosition}`);
    }
  }
}

2. 점진적 구축

// Start simple and build up
{
  "step1": "basic object"
}

// Add complexity gradually
{
  "step1": "basic object",
  "step2": {
    "nested": "object"
  }
}

// Continue until error is found
{
  "step1": "basic object",
  "step2": {
    "nested": "object"
  },
  "step3": [
    "array",
    "elements"
  ]
}

스키마 유효성 검사

JSON 스키마 기초

JSON 스키마는 구문을 넘어 구조적 유효성 검사를 제공합니다:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "email"],
  "additionalProperties": false
}

스키마 유효성 검사 오류

일반적인 스키마 유효성 검사 문제:

// ❌ Schema validation failures
{
  "name": "",           // Too short (minLength: 1)
  "age": -5,            // Below minimum (minimum: 0)
  "email": "invalid",   // Invalid email format
  "extra": "property"   // Not allowed (additionalProperties: false)
}

// ✅ Schema compliant
{
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com"
}

테스트 및 방지

자동화된 유효성 검사 테스트

// Example test suite for JSON validation
const testCases = [
  {
    name: "Valid user object",
    json: '{"name": "John", "age": 30}',
    expectValid: true
  },
  {
    name: "Trailing comma",
    json: '{"name": "John", "age": 30,}',
    expectValid: false
  },
  {
    name: "Single quotes",
    json: "{'name': 'John', 'age': 30}",
    expectValid: false
  }
];

testCases.forEach(test => {
  const isValid = isValidJSON(test.json);
  console.assert(
    isValid === test.expectValid,
    `Test failed: ${test.name}`
  );
});

방지를 위한 최고 관행

방지 전략:

  1. 코드 에디터에서 JSON 린터 사용
  2. CI/CD 파이프라인에서 자동화된 유효성 검사 구현
  3. 구조적 유효성 검사를 위한 JSON 스키마 사용
  4. 정기적으로 에지 케이스 테스트
  5. 처리 전에 사용자 입력 유효성 검사
  6. 애플리케이션에서 적절한 오류 처리 사용

도구 및 리소스

유효성 검사 도구

온라인 유효성 검사기:

  • JSON Validator - 오류 세부 정보와 함께 포괄적인 유효성 검사
  • JSON Formatter - 동시에 형식화 및 유효성 검사
  • JSONLint - 인기 있는 온라인 유효성 검사기

명령줄 도구:

# Using jq for validation
echo '{"valid": "json"}' | jq .

# Using Python
python -m json.tool file.json

# Using Node.js
node -e "JSON.parse(require('fs').readFileSync('file.json'))"

에디터 확장:

  • VS Code: 내장 JSON 유효성 검사
  • Sublime Text: JSON Reindent 패키지
  • Vim: 유효성 검사가 있는 JSON 플러그인

개발 통합

ESLint 규칙

// .eslintrc.js
module.exports = {
  rules: {
    'json/*': ['error', 'allowComments']
  }
};

Pre-commit Hooks

#!/bin/sh
# Validate all JSON files before commit
find . -name "*.json" -exec python -m json.tool {} \; > /dev/null

문제 해결 체크리스트

빠른 진단 단계

  1. 구문 기본 확인:

    • 모든 문자열이 이중 따옴표로
    • 뒤따르는 쉼표 없음
    • 짝이 맞는 대괄호 및 중괄호
    • 유효한 이스케이프 시퀀스
  2. 데이터 유형 유효성 검사:

    • undefined 값 없음
    • 함수나 주석 없음
    • 적절한 숫자 형식
    • 불리언 값이 true/false
  3. 구조 테스트:

    • 중복 키 없음
    • 합리적인 중첩 깊이
    • 유효한 유니코드 문자
  4. 유효성 검사 도구 사용:

    • 온라인 JSON 유효성 검사기
    • 명령줄 확인
    • 적용 가능한 경우 스키마 유효성 검사

복구 전략

JSON이 손상된 경우

// Attempt to recover malformed JSON
function attemptJSONRecovery(malformedJSON) {
  const fixes = [
    // Remove trailing commas
    json => json.replace(/,(\s*[}\]])/g, '$1'),
    
    // Fix single quotes
    json => json.replace(/'/g, '"'),
    
    // Add missing quotes to keys
    json => json.replace(/(\w+):/g, '"$1":'),
  ];
  
  for (const fix of fixes) {
    try {
      const fixed = fix(malformedJSON);
      JSON.parse(fixed);
      return fixed; // Success!
    } catch (e) {
      continue; // Try next fix
    }
  }
  
  throw new Error('Unable to recover JSON');
}

결론

JSON 유효성 검사 오류는 일반적이지만 적절한 지식과 도구로 방지할 수 있습니다. 가장 빈번한 오류 패턴을 이해하고, 적절한 유효성 검사 워크플로를 구현하며, 적절한 디버깅 기술을 사용함으로써 프로젝트에서 JSON 관련 문제를 극적으로 줄일 수 있습니다.

기억하세요: 방지가 디버깅보다 낫습니다. 개발 프로세스 초기에 유효성 검사를 구현하고 프로덕션에 도달하기 전에 오류를 포착하는 자동화 도구를 사용하세요.

JSON 유효성 검사에 도움이 필요하나요? 상세한 오류 분석 및 제안을 위해 JSON Validator Tool을 사용해 보세요.

Published on 2024-01-06 by Development Team