尚無歷史紀錄
在主流程式語言中解析、序列化與操作 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
endrequire '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
endusing 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? Stringimport 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? Stringimport 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 中,不會離開裝置。你可以隨時在歷史側欄中清除。