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

JSON 驗證錯誤:完整疑難排解指南

JSON 驗證錯誤可能令人沮喪且耗時調試。無論您是在處理 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 ',' at position 25 原因:通常是尾隨逗號或錯位標點符號 修復:檢查多餘的逗號、分號或其他標點符號

2. 「JSON 輸入意外結束」

錯誤Unexpected end of JSON input 原因:不完整的 JSON 結構,缺少關閉括號 修復:驗證所有括號和大括號是否正確關閉

3. 「無效字元」錯誤

錯誤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 Schema 基礎

JSON Schema 提供超出語法的結構驗證:

{
  "$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 Schema 進行結構驗證
  4. 定期測試邊緣案例
  5. 在處理前驗證使用者輸入
  6. 在應用程式中使用適當的錯誤處理

工具與資源

驗證工具

線上驗證器:

命令列工具:

# 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']
  }
};

預提交鉤子

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

疑難排解檢查清單

快速診斷步驟

  1. 檢查語法基礎

    • 所有字串使用雙引號
    • 無尾隨逗號
    • 匹配的括號和大括號
    • 有效的轉義序列
  2. 驗證資料類型

    • 無 undefined 值
    • 無函數或註解
    • 適當的數字格式
    • 布林值為 true/false
  3. 測試結構

    • 無重複鍵值
    • 合理的巢狀深度
    • 有效的 Unicode 字元
  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