在线 JSON 解析与格式化工具 — 使用语法高亮和树形视图格式化、校验并浏览 JSON

历史记录

暂无历史记录

输入 JSON 开始解析

JSON 代码示例

在主流编程语言中解析、序列化和操作 JSON 的示例。

// Parse a JSON string into an object
const raw = '{"name":"Alice","age":30,"active":true}';
const user = JSON.parse(raw);
console.log(user.name); // "Alice"

// Convert an object to a formatted JSON string
const data = {
  id: 1,
  tags: ["dev", "api"],
  address: { city: "NYC", zip: "10001" },
  score: null,
};
const pretty = JSON.stringify(data, null, 2);

// Custom replacer — omit sensitive fields
const safe = JSON.stringify(data, (key, val) =>
  key === "id" ? undefined : val
);

// Reviver — transform values during parsing
const parsed = JSON.parse('{"date":"2025-01-15T00:00:00Z"}', (key, val) =>
  key === "date" ? new Date(val) : val
);

// Fetch JSON from an API
const res = await fetch("https://api.example.com/users/1");
const json = await res.json();
// Parse a JSON string into an object
const raw = '{"name":"Alice","age":30,"active":true}';
const user = JSON.parse(raw);
console.log(user.name); // "Alice"

// Convert an object to a formatted JSON string
const data = {
  id: 1,
  tags: ["dev", "api"],
  address: { city: "NYC", zip: "10001" },
  score: null,
};
const pretty = JSON.stringify(data, null, 2);

// Custom replacer — omit sensitive fields
const safe = JSON.stringify(data, (key, val) =>
  key === "id" ? undefined : val
);

// Reviver — transform values during parsing
const parsed = JSON.parse('{"date":"2025-01-15T00:00:00Z"}', (key, val) =>
  key === "date" ? new Date(val) : val
);

// Fetch JSON from an API
const res = await fetch("https://api.example.com/users/1");
const json = await res.json();
import json
from pathlib import Path

# Parse a JSON string
raw = '{"name": "Alice", "age": 30, "active": true}'
user = json.loads(raw)
print(user["name"])  # Alice

# Serialize to a formatted JSON string
data = {
    "id": 1,
    "tags": ["dev", "api"],
    "address": {"city": "NYC", "zip": "10001"},
    "score": None,  # becomes null in JSON
}
pretty = json.dumps(data, indent=2, ensure_ascii=False)

# Read JSON from a file
config = json.loads(Path("config.json").read_text())

# Write JSON to a file
Path("output.json").write_text(
    json.dumps(data, indent=2)
)

# Custom encoder for non-serializable types
from datetime import datetime

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

json.dumps({"now": datetime.now()}, cls=DateEncoder)
import json
from pathlib import Path

# Parse a JSON string
raw = '{"name": "Alice", "age": 30, "active": true}'
user = json.loads(raw)
print(user["name"])  # Alice

# Serialize to a formatted JSON string
data = {
    "id": 1,
    "tags": ["dev", "api"],
    "address": {"city": "NYC", "zip": "10001"},
    "score": None,  # becomes null in JSON
}
pretty = json.dumps(data, indent=2, ensure_ascii=False)

# Read JSON from a file
config = json.loads(Path("config.json").read_text())

# Write JSON to a file
Path("output.json").write_text(
    json.dumps(data, indent=2)
)

# Custom encoder for non-serializable types
from datetime import datetime

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

json.dumps({"now": datetime.now()}, cls=DateEncoder)
// Define a typed interface for JSON data
interface User {
  name: string;
  age: number;
  active: boolean;
  tags: string[];
  address: { city: string; zip: string };
}

// Type-safe parsing with validation
function parseUser(raw: string): User {
  const data: unknown = JSON.parse(raw);
  if (
    typeof data === "object" && data !== null &&
    "name" in data && "age" in data
  ) {
    return data as User;
  }
  throw new Error("Invalid user JSON");
}

// Generic fetch helper with typed response
async function fetchJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json() as Promise<T>;
}

const user = await fetchJson<User>("/api/user/1");

// Partial updates with Pick / Omit
type UserUpdate = Partial<Pick<User, "name" | "age">>;
const patch: UserUpdate = { name: "Bob" };
await fetch("/api/user/1", {
  method: "PATCH",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(patch),
});
// Define a typed interface for JSON data
interface User {
  name: string;
  age: number;
  active: boolean;
  tags: string[];
  address: { city: string; zip: string };
}

// Type-safe parsing with validation
function parseUser(raw: string): User {
  const data: unknown = JSON.parse(raw);
  if (
    typeof data === "object" && data !== null &&
    "name" in data && "age" in data
  ) {
    return data as User;
  }
  throw new Error("Invalid user JSON");
}

// Generic fetch helper with typed response
async function fetchJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json() as Promise<T>;
}

const user = await fetchJson<User>("/api/user/1");

// Partial updates with Pick / Omit
type UserUpdate = Partial<Pick<User, "name" | "age">>;
const patch: UserUpdate = { name: "Bob" };
await fetch("/api/user/1", {
  method: "PATCH",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(patch),
});
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;

public class JsonExample {
    // Define a POJO for JSON mapping
    record User(String name, int age, boolean active, List<String> tags) {}

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // Deserialize JSON string to object
        String raw = """
            {"name":"Alice","age":30,"active":true,"tags":["dev","api"]}
            """;
        User user = gson.fromJson(raw, User.class);
        System.out.println(user.name()); // Alice

        // Serialize object to JSON
        String json = gson.toJson(user);

        // Parse into a generic Map
        Map<String, Object> map = gson.fromJson(raw,
            new TypeToken<Map<String, Object>>(){}.getType());

        // Parse a JSON array
        String arr = """
            [{"name":"Alice"},{"name":"Bob"}]
            """;
        List<User> users = gson.fromJson(arr,
            new TypeToken<List<User>>(){}.getType());
    }
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;

public class JsonExample {
    // Define a POJO for JSON mapping
    record User(String name, int age, boolean active, List<String> tags) {}

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // Deserialize JSON string to object
        String raw = """
            {"name":"Alice","age":30,"active":true,"tags":["dev","api"]}
            """;
        User user = gson.fromJson(raw, User.class);
        System.out.println(user.name()); // Alice

        // Serialize object to JSON
        String json = gson.toJson(user);

        // Parse into a generic Map
        Map<String, Object> map = gson.fromJson(raw,
            new TypeToken<Map<String, Object>>(){}.getType());

        // Parse a JSON array
        String arr = """
            [{"name":"Alice"},{"name":"Bob"}]
            """;
        List<User> users = gson.fromJson(arr,
            new TypeToken<List<User>>(){}.getType());
    }
}
package main

import (
	"encoding/json"
	"fmt"
	"os"
)

// Struct tags control JSON field names
type User struct {
	Name    string   `json:"name"`
	Age     int      `json:"age"`
	Active  bool     `json:"active"`
	Tags    []string `json:"tags,omitempty"`
	Address *Address `json:"address,omitempty"`
}

type Address struct {
	City string `json:"city"`
	Zip  string `json:"zip"`
}

func main() {
	// Unmarshal JSON into a struct
	raw := `{"name":"Alice","age":30,"active":true}`
	var user User
	json.Unmarshal([]byte(raw), &user)
	fmt.Println(user.Name) // Alice

	// Marshal struct to indented JSON
	out, _ := json.MarshalIndent(user, "", "  ")
	fmt.Println(string(out))

	// Decode from a stream (file, HTTP body, etc.)
	file, _ := os.Open("data.json")
	defer file.Close()
	var data User
	json.NewDecoder(file).Decode(&data)

	// Dynamic parsing with map
	var generic map[string]interface{}
	json.Unmarshal([]byte(raw), &generic)
}
package main

import (
	"encoding/json"
	"fmt"
	"os"
)

// Struct tags control JSON field names
type User struct {
	Name    string   `json:"name"`
	Age     int      `json:"age"`
	Active  bool     `json:"active"`
	Tags    []string `json:"tags,omitempty"`
	Address *Address `json:"address,omitempty"`
}

type Address struct {
	City string `json:"city"`
	Zip  string `json:"zip"`
}

func main() {
	// Unmarshal JSON into a struct
	raw := `{"name":"Alice","age":30,"active":true}`
	var user User
	json.Unmarshal([]byte(raw), &user)
	fmt.Println(user.Name) // Alice

	// Marshal struct to indented JSON
	out, _ := json.MarshalIndent(user, "", "  ")
	fmt.Println(string(out))

	// Decode from a stream (file, HTTP body, etc.)
	file, _ := os.Open("data.json")
	defer file.Close()
	var data User
	json.NewDecoder(file).Decode(&data)

	// Dynamic parsing with map
	var generic map[string]interface{}
	json.Unmarshal([]byte(raw), &generic)
}
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

// Derive macros for automatic JSON serialization
#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    age: u32,
    active: bool,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    address: Option<Address>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Address {
    city: String,
    zip: String,
}

fn main() -> serde_json::Result<()> {
    // Deserialize from a JSON string
    let raw = r#"{"name":"Alice","age":30,"active":true}"#;
    let user: User = serde_json::from_str(raw)?;
    println!("{}", user.name); // Alice

    // Serialize to a pretty JSON string
    let json = serde_json::to_string_pretty(&user)?;

    // Build JSON dynamically with the json! macro
    let val = json!({
        "status": "ok",
        "count": 42,
        "items": ["a", "b", "c"]
    });

    // Parse into an untyped Value for dynamic access
    let v: Value = serde_json::from_str(raw)?;
    println!("{}", v["name"]); // "Alice"

    Ok(())
}
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

// Derive macros for automatic JSON serialization
#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    age: u32,
    active: bool,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    address: Option<Address>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Address {
    city: String,
    zip: String,
}

fn main() -> serde_json::Result<()> {
    // Deserialize from a JSON string
    let raw = r#"{"name":"Alice","age":30,"active":true}"#;
    let user: User = serde_json::from_str(raw)?;
    println!("{}", user.name); // Alice

    // Serialize to a pretty JSON string
    let json = serde_json::to_string_pretty(&user)?;

    // Build JSON dynamically with the json! macro
    let val = json!({
        "status": "ok",
        "count": 42,
        "items": ["a", "b", "c"]
    });

    // Parse into an untyped Value for dynamic access
    let v: Value = serde_json::from_str(raw)?;
    println!("{}", v["name"]); // "Alice"

    Ok(())
}
<?php
// Decode a JSON string into an associative array
$raw = '{"name":"Alice","age":30,"active":true}';
$user = json_decode($raw, associative: true);
echo $user['name']; // Alice

// Decode into an object (stdClass)
$obj = json_decode($raw);
echo $obj->name; // Alice

// Encode an array to a formatted JSON string
$data = [
    'id' => 1,
    'tags' => ['dev', 'api'],
    'address' => ['city' => 'NYC', 'zip' => '10001'],
    'score' => null,
];
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Error handling for malformed JSON
$bad = json_decode('invalid json');
if (json_last_error() !== JSON_ERROR_NONE) {
    echo 'Parse error: ' . json_last_error_msg();
}

// Read and write JSON files
$config = json_decode(file_get_contents('config.json'), true);
file_put_contents('output.json', json_encode($data, JSON_PRETTY_PRINT));
<?php
// Decode a JSON string into an associative array
$raw = '{"name":"Alice","age":30,"active":true}';
$user = json_decode($raw, associative: true);
echo $user['name']; // Alice

// Decode into an object (stdClass)
$obj = json_decode($raw);
echo $obj->name; // Alice

// Encode an array to a formatted JSON string
$data = [
    'id' => 1,
    'tags' => ['dev', 'api'],
    'address' => ['city' => 'NYC', 'zip' => '10001'],
    'score' => null,
];
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Error handling for malformed JSON
$bad = json_decode('invalid json');
if (json_last_error() !== JSON_ERROR_NONE) {
    echo 'Parse error: ' . json_last_error_msg();
}

// Read and write JSON files
$config = json_decode(file_get_contents('config.json'), true);
file_put_contents('output.json', json_encode($data, JSON_PRETTY_PRINT));
require 'json'

# Parse a JSON string into a Hash
raw = '{"name":"Alice","age":30,"active":true}'
user = JSON.parse(raw)
puts user['name'] # Alice

# Parse with symbolized keys
user = JSON.parse(raw, symbolize_names: true)
puts user[:name] # Alice

# Generate formatted JSON from a Hash
data = {
  id: 1,
  tags: %w[dev api],
  address: { city: 'NYC', zip: '10001' },
  score: nil  # becomes null in JSON
}
puts JSON.pretty_generate(data)

# Read JSON from a file
config = JSON.parse(File.read('config.json'))

# Write JSON to a file
File.write('output.json', JSON.pretty_generate(data))

# Custom serialization with #to_json
class User
  attr_accessor :name, :age
  def to_json(*args)
    { name: @name, age: @age }.to_json(*args)
  end
end
require 'json'

# Parse a JSON string into a Hash
raw = '{"name":"Alice","age":30,"active":true}'
user = JSON.parse(raw)
puts user['name'] # Alice

# Parse with symbolized keys
user = JSON.parse(raw, symbolize_names: true)
puts user[:name] # Alice

# Generate formatted JSON from a Hash
data = {
  id: 1,
  tags: %w[dev api],
  address: { city: 'NYC', zip: '10001' },
  score: nil  # becomes null in JSON
}
puts JSON.pretty_generate(data)

# Read JSON from a file
config = JSON.parse(File.read('config.json'))

# Write JSON to a file
File.write('output.json', JSON.pretty_generate(data))

# Custom serialization with #to_json
class User
  attr_accessor :name, :age
  def to_json(*args)
    { name: @name, age: @age }.to_json(*args)
  end
end
using System.Text.Json;
using System.Text.Json.Serialization;

// Define a record for JSON mapping
public record User(
    string Name,
    int Age,
    bool Active,
    string[] Tags
);

// Deserialize JSON into a typed object
var raw = """{"name":"Alice","age":30,"active":true,"tags":["dev"]}""";
var opts = new JsonSerializerOptions {
    PropertyNameCaseInsensitive = true
};
var user = JsonSerializer.Deserialize<User>(raw, opts)!;
Console.WriteLine(user.Name); // Alice

// Serialize to indented JSON
var json = JsonSerializer.Serialize(user, new JsonSerializerOptions {
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});

// Parse dynamic JSON with JsonDocument
using var doc = JsonDocument.Parse(raw);
var root = doc.RootElement;
var name = root.GetProperty("name").GetString();

// Work with JsonNode for mutable access
var node = JsonNode.Parse(raw)!;
node["age"] = 31;
Console.WriteLine(node.ToJsonString());
using System.Text.Json;
using System.Text.Json.Serialization;

// Define a record for JSON mapping
public record User(
    string Name,
    int Age,
    bool Active,
    string[] Tags
);

// Deserialize JSON into a typed object
var raw = """{"name":"Alice","age":30,"active":true,"tags":["dev"]}""";
var opts = new JsonSerializerOptions {
    PropertyNameCaseInsensitive = true
};
var user = JsonSerializer.Deserialize<User>(raw, opts)!;
Console.WriteLine(user.Name); // Alice

// Serialize to indented JSON
var json = JsonSerializer.Serialize(user, new JsonSerializerOptions {
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});

// Parse dynamic JSON with JsonDocument
using var doc = JsonDocument.Parse(raw);
var root = doc.RootElement;
var name = root.GetProperty("name").GetString();

// Work with JsonNode for mutable access
var node = JsonNode.Parse(raw)!;
node["age"] = 31;
Console.WriteLine(node.ToJsonString());
import Foundation

// Define a Codable struct for JSON mapping
struct User: Codable {
    let name: String
    let age: Int
    let active: Bool
    let tags: [String]?
}

// Decode JSON data into a struct
let raw = #"{"name":"Alice","age":30,"active":true}"#
let data = raw.data(using: .utf8)!
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
print(user.name) // Alice

// Encode struct to formatted JSON
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let json = try encoder.encode(user)
print(String(data: json, encoding: .utf8)!)

// Custom key mapping with CodingKeys
struct ApiResponse: Codable {
    let userId: Int
    let createdAt: String

    enum CodingKeys: String, CodingKey {
        case userId = "user_id"
        case createdAt = "created_at"
    }
}

// Dynamic parsing with JSONSerialization
let obj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
let name = obj["name"] as? String
import Foundation

// Define a Codable struct for JSON mapping
struct User: Codable {
    let name: String
    let age: Int
    let active: Bool
    let tags: [String]?
}

// Decode JSON data into a struct
let raw = #"{"name":"Alice","age":30,"active":true}"#
let data = raw.data(using: .utf8)!
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
print(user.name) // Alice

// Encode struct to formatted JSON
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let json = try encoder.encode(user)
print(String(data: json, encoding: .utf8)!)

// Custom key mapping with CodingKeys
struct ApiResponse: Codable {
    let userId: Int
    let createdAt: String

    enum CodingKeys: String, CodingKey {
        case userId = "user_id"
        case createdAt = "created_at"
    }
}

// Dynamic parsing with JSONSerialization
let obj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
let name = obj["name"] as? String
import kotlinx.serialization.*
import kotlinx.serialization.json.*

// Data class with serialization annotations
@Serializable
data class User(
    val name: String,
    val age: Int,
    val active: Boolean,
    val tags: List<String> = emptyList()
)

fun main() {
    val json = Json { prettyPrint = true; ignoreUnknownKeys = true }

    // Deserialize JSON string to object
    val raw = """{"name":"Alice","age":30,"active":true}"""
    val user = json.decodeFromString<User>(raw)
    println(user.name) // Alice

    // Serialize object to JSON
    val output = json.encodeToString(user)

    // Dynamic parsing with JsonElement
    val element = json.parseToJsonElement(raw)
    val name = element.jsonObject["name"]?.jsonPrimitive?.content

    // Build JSON dynamically
    val built = buildJsonObject {
        put("status", "ok")
        put("count", 42)
        putJsonArray("items") {
            add("a"); add("b"); add("c")
        }
    }
    println(json.encodeToString(built))
}
import kotlinx.serialization.*
import kotlinx.serialization.json.*

// Data class with serialization annotations
@Serializable
data class User(
    val name: String,
    val age: Int,
    val active: Boolean,
    val tags: List<String> = emptyList()
)

fun main() {
    val json = Json { prettyPrint = true; ignoreUnknownKeys = true }

    // Deserialize JSON string to object
    val raw = """{"name":"Alice","age":30,"active":true}"""
    val user = json.decodeFromString<User>(raw)
    println(user.name) // Alice

    // Serialize object to JSON
    val output = json.encodeToString(user)

    // Dynamic parsing with JsonElement
    val element = json.parseToJsonElement(raw)
    val name = element.jsonObject["name"]?.jsonPrimitive?.content

    // Build JSON dynamically
    val built = buildJsonObject {
        put("status", "ok")
        put("count", 42)
        putJsonArray("items") {
            add("a"); add("b"); add("c")
        }
    }
    println(json.encodeToString(built))
}

功能亮点

语法高亮

用颜色区分字符串、数字、布尔值、null 和键,让复杂 JSON 结构一眼可读。

可折叠树形视图

交互式展开和折叠嵌套对象与数组。深入浏览复杂结构时也不会丢失上下文。

缩略图导航

用可视化缩略图概览整个 JSON 文档。点击缩略图任意位置即可立即跳转。

格式化与校验

自动将杂乱 JSON 按正确缩进格式化,或校验并用清晰的错误信息定位语法问题。

本地历史记录

所有解析过的 JSON 文档都会保存在浏览器本地 IndexedDB 中。可随时浏览、搜索并恢复历史会话。

路径复制与类型信息

点击任意键或值即可复制其 JSON 路径。每个节点都会显示数据类型和数组长度,便于快速检查。

常见问题

JSON(JavaScript Object Notation)是一种轻量级数据交换格式,便于人类读写,也便于机器解析和生成。它广泛用于 Web API、配置文件和数据存储。

不会。所有解析、格式化和校验都完全在浏览器内通过 JavaScript 完成。你的数据不会离开设备,没有服务器请求,也没有数据收集。

这个工具支持语法高亮、可折叠树形视图、缩略图导航、自动格式化、带错误提示的校验、JSON 路径复制、基于 IndexedDB 的本地历史记录,以及可调整大小的分栏布局。

可以。该工具使用虚拟化渲染和缩略图来高效浏览大型文档。性能取决于浏览器和设备,但可以流畅处理包含数千行的文件。

你的 JSON 历史记录会保存在浏览器本地 IndexedDB 中,不会离开设备。你可以随时在历史侧栏中清空它。

持续增长的高效、隐私优先开发者工具集合。所有工具都在浏览器中运行,数据不会离开你的设备。

工具

JSON 解析器JSON Schema 校验器JSON 转换器JSON 转 TypeScriptOpenAPI 查看器代码格式化SQL 格式化cURL 转换器时间戳转换器Cron 解析器URL 编码器二维码工具IP 与 CIDR 计算器Gzip 与 Deflate 工具JWT 解码器JWT 验签与 JWK 工具哈希生成器密码与 TOTPBase64 编码器UUID 生成器图片元数据图片压缩Tiny 图片压缩器图片工具箱 Pro屏幕录制正则测试器文本 DiffMarkdown 与 Mermaid 预览颜色与对比度工具

法律

隐私政策服务条款

© 2026 ZPTools. 保留所有权利。