📅 2026-03-24⏱ 阅读约 15 分钟👤 适合所有开发者
本文目录
JSON 的最大优势之一就是跨语言通用性——同一份数据,可以由 Python 后端生成,传给 JavaScript 前端使用,再被 Java 服务消费,完全无障碍。本文为每种主流语言提供完整的 JSON 处理代码,包含解析、序列化、文件读写、错误处理和常见陷阱。
1. JavaScript / Node.js
JavaScript 对 JSON 的支持最为原生,因为 JSON 语法本就来源于 JavaScript 对象字面量。JSON 是全局对象,无需任何导入。
🟨
JavaScript / Node.js
原生支持,内置 JSON 全局对象
基础解析与序列化
// JSON 字符串 → JavaScript 对象
const jsonStr = '{"name":"张三","age":28,"hobbies":["编程","阅读"]}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // "张三"
console.log(obj.hobbies[0]); // "编程"
// JavaScript 对象 → JSON 字符串
const data = { name: "李四", age: 32, active: true };
const json = JSON.stringify(data);
// '{"name":"李四","age":32,"active":true}'
// 格式化输出(第2参数为replacer,第3参数为缩进)
const pretty = JSON.stringify(data, null, 2);
// {
// "name": "李四",
// "age": 32,
// "active": true
// }
高级用法:replacer 和 reviver
// replacer:控制哪些字段被序列化
const user = { name: "张三", password: "secret123", age: 28 };
const safe = JSON.stringify(user, ["name", "age"]); // 只序列化 name 和 age
// '{"name":"张三","age":28}'
// reviver:解析时转换值(常用于日期还原)
const withDate = '{"name":"张三","createdAt":"2024-01-15T10:00:00Z"}';
const parsed = JSON.parse(withDate, (key, value) => {
if (key === 'createdAt') return new Date(value);
return value;
});
console.log(parsed.createdAt instanceof Date); // true
Node.js 文件读写
const fs = require('fs');
// 读取 JSON 文件(同步)
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
// 读取 JSON 文件(异步)
fs.readFile('./data.json', 'utf8', (err, data) => {
if (err) throw err;
const json = JSON.parse(data);
});
// 写入 JSON 文件
const output = { users: [{ id: 1, name: "张三" }] };
fs.writeFileSync('./output.json', JSON.stringify(output, null, 2), 'utf8');
错误处理
// JSON.parse 失败时抛出 SyntaxError
try {
const data = JSON.parse("这不是JSON{");
} catch (e) {
if (e instanceof SyntaxError) {
console.error("JSON 解析失败:", e.message);
}
}
// 安全解析函数(不抛异常)
function safeJsonParse(str, fallback = null) {
try { return JSON.parse(str); }
catch { return fallback; }
}
注意:大数字精度问题
// JavaScript 的 Number 类型是 64位浮点数
// 超过 2^53 的整数会丢失精度
const bigId = JSON.parse('{"id": 9007199254740993}');
console.log(bigId.id); // 9007199254740992 ← 精度丢失!
// 解决方案:用字符串传递大整数
const bigId2 = JSON.parse('{"id": "9007199254740993"}');
console.log(bigId2.id); // "9007199254740993" ← 正确
2. Python
Python 内置 json 标准库,功能完整稳定,处理中文时需要注意 ensure_ascii 参数。
🐍
Python
内置 json 标准库,无需安装
基础解析与序列化
import json
# JSON 字符串 → Python 字典
json_str = '{"name": "张三", "age": 28, "active": true}'
data = json.loads(json_str)
print(data['name']) # 张三
print(data['active']) # True(注意:JSON true → Python True)
# Python 字典 → JSON 字符串
output = {"name": "李四", "scores": [95, 87, 92]}
# ensure_ascii=False 使中文不被转义为 \uXXXX
compact = json.dumps(output, ensure_ascii=False)
# '{"name": "李四", "scores": [95, 87, 92]}'
# 格式化输出
pretty = json.dumps(output, ensure_ascii=False, indent=2, sort_keys=True)
文件读写
import json
# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f) # 注意:load() 而非 loads()
# 写入 JSON 文件
result = {"status": "ok", "count": 42, "items": []}
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
类型映射关系
# Python ↔ JSON 类型对应关系:
# dict ↔ object {}
# list/tuple ↔ array []
# str ↔ string ""
# int/float ↔ number
# True/False ↔ true/false
# None ↔ null
# 注意:Python tuple 序列化后成为 JSON 数组
data = {"coords": (39.9, 116.4)}
print(json.dumps(data)) # {"coords": [39.9, 116.4]}
自定义对象的序列化
from datetime import datetime
import json
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
data = {"name": "张三", "created": datetime.now()}
json_str = json.dumps(data, cls=DateTimeEncoder, ensure_ascii=False)
# {"name": "张三", "created": "2024-01-15T10:30:00.123456"}
错误处理
import json
try:
data = json.loads("invalid json {")
except json.JSONDecodeError as e:
print(f"错误信息: {e.msg}") # Expecting value
print(f"错误位置: 行{e.lineno} 列{e.colno}")
print(f"字符偏移: {e.pos}")
3. Java(Jackson & Gson)
Java 没有内置 JSON 支持,通常使用 Jackson(Spring Boot 默认)或 Gson(Google 出品)。两者都非常成熟。
☕
Java
推荐 Jackson(功能全)或 Gson(轻量)
Jackson 基础用法
// Maven 依赖
// <dependency>
// <groupId>com.fasterxml.jackson.core</groupId>
// <artifactId>jackson-databind</artifactId>
// <version>2.15.0</version>
// </dependency>
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
// JSON 字符串 → Java 对象(POJO)
String json = "{"name":"张三","age":28}";
User user = mapper.readValue(json, User.class);
// JSON 字符串 → Map(无需定义类)
Map<String, Object> map = mapper.readValue(json, Map.class);
// Java 对象 → JSON 字符串
String output = mapper.writeValueAsString(user);
// 格式化输出
String pretty = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(user);
Jackson 注解(常用)
import com.fasterxml.jackson.annotation.*;
public class User {
@JsonProperty("user_name") // 指定 JSON 字段名
private String name;
@JsonIgnore // 序列化时忽略此字段
private String password;
@JsonInclude(JsonInclude.Include.NON_NULL) // null 时不输出
private String nickname;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createdAt;
}
Gson 基础用法
// Maven 依赖
// <dependency>
// <groupId>com.google.code.gson</groupId>
// <artifactId>gson</artifactId>
// <version>2.10.1</version>
// </dependency>
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
// 解析
User user = gson.fromJson(jsonString, User.class);
// 序列化
String json = gson.toJson(user);
4. Go
Go 标准库 encoding/json 简洁高效,利用结构体标签(struct tags)灵活控制序列化行为。
🐹
Go
标准库 encoding/json,零依赖
package main
import (
"encoding/json"
"fmt"
"os"
"time"
)
// 结构体定义,json 标签控制字段名
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"` // 空值时省略
Password string `json:"-"` // 永远不序列化
CreatedAt time.Time `json:"created_at"`
}
func main() {
// 解析 JSON
jsonStr := []byte(`{"id":1,"name":"张三","created_at":"2024-01-15T10:00:00Z"}`)
var user User
if err := json.Unmarshal(jsonStr, &user); err != nil {
fmt.Println("解析错误:", err)
return
}
fmt.Println(user.Name) // 张三
// 序列化
data, err := json.Marshal(user) // 紧凑
data, err = json.MarshalIndent(user, "", " ") // 格式化
// 读取 JSON 文件
file, _ := os.Open("data.json")
defer file.Close()
decoder := json.NewDecoder(file)
var result map[string]interface{}
decoder.Decode(&result)
// 处理动态 JSON(任意结构)
var dynamic interface{}
json.Unmarshal(jsonStr, &dynamic)
m := dynamic.(map[string]interface{})
fmt.Println(m["name"]) // 张三
}
5. PHP
🐘
PHP
内置 json_encode / json_decode 函数
<?php
// 解析 JSON 字符串
$jsonStr = '{"name":"张三","age":28,"active":true}';
// 解析为数组(第2参数 true)
$arr = json_decode($jsonStr, true);
echo $arr['name']; // 张三
// 解析为对象
$obj = json_decode($jsonStr);
echo $obj->name; // 张三
// 错误处理
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON 解析错误: " . json_last_error_msg();
}
// PHP 数组 → JSON 字符串
$data = ["name" => "李四", "scores" => [95, 87, 92]];
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// JSON_UNESCAPED_UNICODE 让中文不被转义为 \uXXXX
// 读取 JSON 文件
$content = file_get_contents('data.json');
$data = json_decode($content, true);
// 写入 JSON 文件
file_put_contents('output.json',
json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
);
6. Swift
🍎
Swift
Codable 协议,类型安全
import Foundation
// 定义 Codable 结构体
struct User: Codable {
let id: Int
let name: String
let email: String? // Optional 对应 JSON null
let createdAt: Date
// 自定义 JSON 字段名
enum CodingKeys: String, CodingKey {
case id, name, email
case createdAt = "created_at"
}
}
// 解析 JSON
let jsonStr = """
{"id":1,"name":"张三","created_at":"2024-01-15T10:00:00Z"}
"""
let jsonData = jsonStr.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601 // 日期解析策略
do {
let user = try decoder.decode(User.self, from: jsonData)
print(user.name) // 张三
} catch {
print("解析错误: (error)")
}
// 序列化
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(user)
let outputStr = String(data: data, encoding: .utf8)!
各语言横向对比
| 语言 | JSON 支持方式 | 解析函数 | 序列化函数 | 中文处理 |
|---|---|---|---|---|
| JavaScript | 原生内置 | JSON.parse() | JSON.stringify() | 自动支持 |
| Python | 标准库 json | json.loads() | json.dumps() | 需设 ensure_ascii=False |
| Java | 第三方库(Jackson/Gson) | readValue() | writeValueAsString() | 自动支持 |
| Go | 标准库 encoding/json | json.Unmarshal() | json.Marshal() | 自动支持 |
| PHP | 内置函数 | json_decode() | json_encode() | 需设 JSON_UNESCAPED_UNICODE |
| Swift | Foundation Codable | decoder.decode() | encoder.encode() | 自动支持 |
💡 无论哪种语言,在处理从外部获取的 JSON 数据前,都建议用 JSON验证工具 先检查数据格式是否正确,节省调试时间。