当前位置: 首页 > news >正文

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

通用注意事项

  1. 编码问题:确保 JSON 文件使用 UTF-8 编码。
  2. 数据类型映射:不同语言中 JSON 类型与本地类型的转换可能不同(如 Python 的 tuple → JSON 数组)。
  3. 错误处理:解析非法 JSON 时会抛出异常,务必添加异常处理逻辑。
  4. 性能:对大文件处理时,考虑流式解析(如 Python 的 ijson、Java 的 JsonParser)。

选择适合你的语言和库,即可在 Linux 中高效处理 JSON 数据。

相关文章:

  • buuctf——web刷题第二页
  • 深入解析CI/CD开发流程
  • Elasticsearch最新入门教程
  • 【C++进阶篇】C++11新特性(中篇)
  • 【Python3教程】Python3基础篇之错误和异常
  • 【汇编逆向系列】六、函数调用包含多个参数之多个整型-参数压栈顺序,rcx,rdx,r8,r9寄存器
  • Go语言底层(三): sync 锁 与 对象池
  • 华为云CentOS配置在线yum源,连接公网后,逐步复制粘贴,看好自己对应的版本即可,【新手必看】
  • 【Zephyr 系列 9】Zephyr 与设备树机制详解:如何为你的板子编写 Devicetree
  • Linux系统编程-DAY10(TCP操作)
  • java32
  • python变量
  • 【Go语言基础】基本语法
  • Linux(12)——基础IO(下)
  • 优化学习笔记
  • Unity协程Coroutine与UniTask对比
  • TIA博途中的程序导出为PDF格式的具体方法示例
  • 2025年牛客网秋招/社招高质量 Java 面试八股文整理
  • Linux免杀方案汇总(C语言)
  • 力扣100题之128. 最长连续序列
  • 贵阳网站建设设计公司哪家好/十大计算机培训学校
  • 做电商网站外包/百度seo 优化
  • 郴州网站建设/网站排名优化培训
  • 贵阳做网站的/关键词搜索点击软件
  • 网站空间控制面板软件/怎么做优化关键词
  • 做h5的免费软件/上海官网seo