Linux下JSON序列化与反序列化方法
在 Linux 环境下,JSON 的序列化(对象 → JSON 字符串)和反序列化(JSON 字符串 → 对象)通常通过编程语言的标准库或第三方库实现。以下是常用语言的实现方式:
1. Python(推荐库:json
)
序列化
import jsondata = {"name": "Alice","age": 30,"hobbies": ["coding", "reading"]
}# 对象 → JSON 字符串
json_str = json.dumps(data)
print(json_str) # 输出:{"name": "Alice", "age": 30, "hobbies": ["coding", "reading"]}# 写入文件
with open("data.json", "w") as f:json.dump(data, f)
反序列化
import json# JSON 字符串 → 对象
json_str = '{"name": "Alice", "age": 30, "hobbies": ["coding", "reading"]}'
data = json.loads(json_str)
print(data["name"]) # 输出:Alice# 从文件读取
with open("data.json", "r") as f:data_from_file = json.load(f)
2. JavaScript/Node.js(内置 JSON
对象)
序列化
const data = {name: "Bob",age: 25,skills: ["JavaScript", "Linux"]
};// 对象 → JSON 字符串
const jsonStr = JSON.stringify(data);
console.log(jsonStr); // 输出:{"name":"Bob","age":25,"skills":["JavaScript","Linux"]}// 写入文件(需 fs 模块)
const fs = require('fs');
fs.writeFileSync('data.json', jsonStr);
反序列化
const jsonStr = '{"name":"Bob","age":25,"skills":["JavaScript","Linux"]}';// JSON 字符串 → 对象
const data = JSON.parse(jsonStr);
console.log(data.name); // 输出:Bob// 从文件读取
const dataFromFile = JSON.parse(fs.readFileSync('data.json', 'utf8'));
3. C++(推荐库:nlohmann/json
)
安装库
# Debian/Ubuntu
sudo apt install nlohmann-json3-dev
序列化
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;int main() {// 创建 JSON 对象json j;j["name"] = "Charlie";j["score"] = 95;j["courses"] = {"Math", "Physics"};// 对象 → JSON 字符串std::string json_str = j.dump();std::cout << json_str << std::endl;// 写入文件std::ofstream("data.json") << j;
}
反序列化
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;int main() {// 从字符串解析auto data = json::parse(R"({"name":"Charlie","score":95})");std::cout << data["name"] << std::endl; // 输出:Charlie// 从文件读取std::ifstream f("data.json");json data_from_file = json::parse(f);
}
4. Java(推荐库:Jackson
)
添加依赖(Maven)
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.0</version>
</dependency>
序列化
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;public class Main {public static void main(String[] args) {ObjectMapper mapper = new ObjectMapper();User user = new User("David", 28);try {// 对象 → JSON 字符串String jsonStr = mapper.writeValueAsString(user);System.out.println(jsonStr); // 输出:{"name":"David","age":28}// 写入文件mapper.writeValue(new File("data.json"), user);} catch (Exception e) {e.printStackTrace();}}
}class User {public String name;public int age;public User(String name, int age) {this.name = name;this.age = age;}
}
反序列化
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;public class Main {public static void main(String[] args) {ObjectMapper mapper = new ObjectMapper();String jsonStr = "{\"name\":\"David\",\"age\":28}";try {// JSON 字符串 → 对象User user = mapper.readValue(jsonStr, User.class);System.out.println(user.name); // 输出:David// 从文件读取User userFromFile = mapper.readValue(new File("data.json"), User.class);} catch (Exception e) {e.printStackTrace();}}
}
5. Bash(使用 jq
工具)
安装
sudo apt install jq # Debian/Ubuntu
sudo yum install jq # CentOS/RHEL
序列化
# 手动构造 JSON(简单场景)
echo '{"name": "Eve", "active": true}' > data.json# 使用 jq 生成(复杂数据需外部输入)
jq -n '{name: "Eve", active: true}' > data.json
反序列化
# 解析并提取字段
name=$(jq -r '.name' data.json)
echo $name # 输出:Eve# 格式化输出
jq . data.json
通用注意事项
- 编码问题:确保 JSON 文件使用 UTF-8 编码。
- 数据类型映射:不同语言中 JSON 类型与本地类型的转换可能不同(如 Python 的
tuple
→ JSON 数组)。 - 错误处理:解析非法 JSON 时会抛出异常,务必添加异常处理逻辑。
- 性能:对大文件处理时,考虑流式解析(如 Python 的
ijson
、Java 的JsonParser
)。
选择适合你的语言和库,即可在 Linux 中高效处理 JSON 数据。