K
ken
首页文章🕐 时间转换📋 JSON 工具🖼️ Base64 图片🔑 密码生成 Cron 表达式🔤 命名转换📱 二维码生成#️⃣ 哈希计算🔡 编码转换🔍 正则表达式⚙️ 配置文件格式转化🔐 加解密⚖️ BMI 计算🎲 随机数据🗜️ 图片工具🌍 世界时钟🏛️ 罗马数字🔢 数字转中文💰 贷款计算
FrontendHOT

What is JSON? How to Format, Validate and Parse JSON Data

2026-04-23·6 分钟阅读

Why JSON Won

I have been writing APIs for eight years, and I have seen data formats come and go. XML was the standard when I started — verbose, namespaced, and painful to read. YAML is pleasant for config files but a nightmare for API responses (significant whitespace in a data interchange format? no thanks).

JSON struck the right balance. It is readable enough for a human to scan, strict enough for a machine to parse reliably, and simple enough that implementing a parser from scratch takes an afternoon.

Here is what you need to know to use it well.

JSON Basic Structure

JSON has only two structures, and understanding this makes everything else easier.

Key-value pair collection (object): Wrapped in curly braces {}, keys are strings, values can be any type.

json双击代码复制
{"name": "Ken", "age": 30, "active": true}

Ordered value list (array): Wrapped in square brackets [], values can be any type.

json双击代码复制
["apple", "banana", "cherry"]

Objects nest inside arrays, arrays nest inside objects. Every JSON document starts with either {} or [].

JSON Data Types

JSON supports exactly 6 data types. There is no date type, no undefined, no binary — you represent those as strings or numbers by convention.

  • String: Double-quoted only, e.g. "hello"
  • Number: Integer or float, e.g. 42, 3.14
  • Boolean: true or false
  • null: Represents empty value
  • Object: Key-value pair collection
  • Array: Ordered value list
  • The strictness catches beginners. In JavaScript you can write {name: "Ken"} but JSON requires {"name": "Ken"}. Single quotes are invalid. Trailing commas will break your parser. These rules exist because JSON is designed for cross-language data exchange — it has to be unambiguous.

    Common JSON Errors

    1. Trailing Commas

    json双击代码复制
    {"a": 1, "b": 2,}  // Invalid
    {"a": 1, "b": 2}   // Valid

    This is the most common JSON error I see in code reviews. In JavaScript, trailing commas in objects are legal since ES5. In JSON, they are not. Your fetch response will fail silently and you will spend twenty minutes debugging.

    2. Unquoted Keys

    json双击代码复制
    {name: "Ken"}  // Invalid
    {"name": "Ken"}  // Valid

    3. Single Quotes

    json双击代码复制
    {'name': 'Ken'}  // Invalid
    {"name": "Ken"}  // Valid

    4. Nested Complexity

    A less obvious issue: deeply nested JSON (4+ levels) becomes unreadable fast.

    json双击代码复制
    {
      "user": {
        "profile": {
          "settings": {
            "notifications": {
              "email": true
            }
          }
        }
      }
    }

    When you need to access user.profile.settings.notifications.email, something has gone wrong with your schema design. Consider flattening or splitting into separate resources.

    How to Format JSON in Code

    Pretty-printing JSON is essential during development. Every language has a built-in way:

    javascript双击代码复制
    // JavaScript
    const formatted = JSON.stringify(obj, null, 2)
    python双击代码复制
    # Python
    import json
    formatted = json.dumps(obj, indent=2)
    go双击代码复制
    // Go
    import "encoding/json"
    data, _ := json.MarshalIndent(obj, "", "  ")

    The second parameter (null or "" ) is a replacer or prefix, and the third is the indentation string. Use 2 spaces — tabs in JSON files will annoy your teammates.

    JSON in the Real World

    API Responses

    Every REST API I have consumed in the last five years returned JSON. The pattern is always the same:

    json双击代码复制
    {
      "status": 200,
      "data": { ... },
      "meta": {
        "page": 1,
        "total": 42
      }
    }

    Consistent response structure matters more than you think. When every endpoint returns a different shape, your frontend error handling becomes a tangle of optional chaining and null checks.

    Configuration Files

    VS Code settings.json, tsconfig.json, package.json — modern tooling runs on JSON. One practical tip: keep your package.json dependencies alphabetized. It makes merge conflicts easier to resolve.

    When Not to Use JSON

    JSON has limits. It has no comments, so complex configuration with explanations should use YAML or TOML. It has no schema enforcement by default — validate incoming JSON with tools like JSON Schema or Zod. And for high-performance logging, JSON is verbose; consider protobuf or msgpack for throughput-sensitive paths.

    JSON Validation

    Catching invalid JSON early saves debugging time. The fastest way: paste into any JSON validator. For automated validation in your CI pipeline:

    bash双击代码复制
    # Validate JSON files in CI
    echo '{"key": "value"}' | python3 -m json.tool
    # If invalid, this command exits with non-zero status

    For JavaScript projects, I rely on AJV (Another JSON Validator) with JSON Schema:

    javascript双击代码复制
    import Ajv from "ajv"
    const ajv = new Ajv()
    
    const schema = {
      type: "object",
      properties: {
        name: { type: "string" },
        age: { type: "integer", minimum: 0 }
      },
      required: ["name", "age"]
    }
    
    const validate = ajv.compile(schema)
    validate({ name: "Ken", age: 30 }) // true
    validate({ name: "Ken", age: -1 }) // false

    JSON Security

    JSON has security considerations that many developers overlook.

    Prototype Pollution

    When parsing JSON in JavaScript, never use the dangerous object literal pattern:

    javascript双击代码复制
    // Dangerous
    const data = eval("(" + jsonString + ")")
    
    // Safe
    const data = JSON.parse(jsonString)

    Too Deep Nesting Attacks

    An attacker can send deeply nested JSON to cause a stack overflow in your parser. Set a depth limit:

    javascript双击代码复制
    const data = JSON.parse(jsonString, (key, value) => {
      return value
    }, 512) // Max depth

    Wrapping Up

    JSON is not the newest or the fastest data format, but it is the most universal. Learn its quirks early — the strict quoting rules, the lack of comments, the no-trailing-comma rule — and they will never surprise you in production.

    Conclusion

    JSON is everywhere because it works. Learn its syntax rules, keep your nesting shallow, validate at the boundary, and pretty-print during development. That is 90% of what you need to know.