各主流编程语言处理 JSON 完整指南

张开发
2026/5/2 14:02:35 15 分钟阅读

分享文章

各主流编程语言处理 JSON 完整指南
本文目录JavaScript / Node.jsPythonJavaJackson GsonGoPHPSwift各语言横向对比JSON 的最大优势之一就是跨语言通用性——同一份数据可以由 Python 后端生成传给 JavaScript 前端使用再被 Java 服务消费完全无障碍。本文为每种主流语言提供完整的 JSON 处理代码包含解析、序列化、文件读写、错误处理和常见陷阱。1. JavaScript / Node.jsJavaScript 对 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); // trueNode.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. PythonPython 内置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_asciiFalse 使中文不被转义为 \uXXXX compact json.dumps(output, ensure_asciiFalse) # {name: 李四, scores: [95, 87, 92]} # 格式化输出 pretty json.dumps(output, ensure_asciiFalse, indent2, sort_keysTrue)文件读写import json # 读取 JSON 文件 with open(data.json, r, encodingutf-8) as f: data json.load(f) # 注意load() 而非 loads() # 写入 JSON 文件 result {status: ok, count: 42, items: []} with open(output.json, w, encodingutf-8) as f: json.dump(result, f, ensure_asciiFalse, indent2)类型映射关系# 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, clsDateTimeEncoder, ensure_asciiFalse) # {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. JavaJackson GsonJava 没有内置 JSON 支持通常使用 JacksonSpring Boot 默认或 GsonGoogle 出品。两者都非常成熟。☕Java推荐 Jackson功能全或 Gson轻量Jackson 基础用法// Maven 依赖 // dependency // groupIdcom.fasterxml.jackson.core/groupId // artifactIdjackson-databind/artifactId // version2.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无需定义类 MapString, 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 // groupIdcom.google.code.gson/groupId // artifactIdgson/artifactId // version2.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. GoGo 标准库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. PHPPHP内置 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. SwiftSwiftCodable 协议类型安全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标准库 jsonjson.loads()json.dumps()需设 ensure_asciiFalseJava第三方库Jackson/GsonreadValue()writeValueAsString()自动支持Go标准库 encoding/jsonjson.Unmarshal()json.Marshal()自动支持PHP内置函数json_decode()json_encode()需设 JSON_UNESCAPED_UNICODESwiftFoundation Codabledecoder.decode()encoder.encode()自动支持 无论哪种语言在处理从外部获取的 JSON 数据前都建议用 JSON验证工具 先检查数据格式是否正确节省调试时间。相关文章推荐 什么是JSON完整入门指南 JSON错误排查10种常见错误修复⚖️ JSON vs XML vs YAML格式深度对比 JSON进阶技巧Schema验证与JSONPath JSON与REST APIAPI设计最佳实践

更多文章