JSON处理教程

全面覆盖Python、JavaScript、Java、Go、PHP、C#等主流编程语言的JSON处理方法。

🐍

Python JSON处理

Python内置json模块,使用简单方便

解析JSON

import json

# 解析JSON字符串
json_str = '{"name": "张三", "age": 25}'
data = json.loads(json_str)
print(data['name'])  # 输出: 张三

# 读取JSON文件
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print(data)

生成JSON

import json

# 将Python对象转为JSON字符串
data = {"name": "张三", "age": 25}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)

# 写入JSON文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

实用技巧

  • 使用 ensure_ascii=False 保留中文字符
  • 使用 indent 参数美化输出
  • 使用 object_hook 自定义反序列化
🟨

JavaScript JSON处理

JavaScript原生支持JSON,无需额外库

解析JSON

// 解析JSON字符串
const jsonStr = '{"name": "张三", "age": 25}';
const data = JSON.parse(jsonStr);
console.log(data.name);  // 输出: 张三

// 处理解析错误
try {
  const data = JSON.parse(jsonStr);
} catch (error) {
  console.error('JSON解析失败:', error.message);
}

生成JSON

// 将JavaScript对象转为JSON字符串
const data = { name: "张三", age: 25 };
const jsonStr = JSON.stringify(data, null, 2);
console.log(jsonStr);

// 自定义序列化
const jsonStr = JSON.stringify(data, (key, value) => {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value;
}, 2);

实用技巧

  • JSON.parse() 解析失败会抛出异常
  • JSON.stringify() 自动忽略undefined和函数
  • 使用 replacer 参数自定义序列化

Java JSON处理

推荐使用Jackson或Gson库处理JSON

解析JSON (Jackson)

import com.fasterxml.jackson.databind.ObjectMapper;

// 创建ObjectMapper
ObjectMapper mapper = new ObjectMapper();

// 解析JSON字符串
String json = "{\"name\": \"张三\", \"age\": 25}";
User user = mapper.readValue(json, User.class);
System.out.println(user.getName());

// 解析JSON文件
User user = mapper.readValue(new File("data.json"), User.class);

生成JSON (Jackson)

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();

// 将Java对象转为JSON字符串
User user = new User("张三", 25);
String json = mapper.writeValueAsString(user);

// 美化输出
String prettyJson = mapper.writerWithDefaultPrettyPrinter()
                          .writeValueAsString(user);

// 写入文件
mapper.writeValue(new File("output.json"), user);

实用技巧

  • Jackson性能优秀,Spring Boot默认使用
  • 使用@JsonProperty自定义字段名
  • 使用@JsonIgnore忽略字段
🔵

Go JSON处理

Go标准库encoding/json功能完善

解析JSON

import "encoding/json"

// 定义结构体
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

// 解析JSON字符串
jsonStr := `{"name": "张三", "age": 25}`
var user User
err := json.Unmarshal([]byte(jsonStr), &user)
if err != nil {
    panic(err)
}
fmt.Println(user.Name)  // 输出: 张三

生成JSON

import "encoding/json"

// 将结构体转为JSON
user := User{Name: "张三", Age: 25}
jsonBytes, err := json.Marshal(user)
if err != nil {
    panic(err)
}
fmt.Println(string(jsonBytes))

// 美化输出
prettyJSON, _ := json.MarshalIndent(user, "", "  ")
fmt.Println(string(prettyJSON))

实用技巧

  • 使用json tag指定JSON字段名
  • json.Marshal返回[]byte
  • 使用json.RawMessage延迟解析
🐘

PHP JSON处理

PHP内置json_encode/json_decode函数

解析JSON

<?php
// 解析JSON字符串
$jsonStr = '{"name": "张三", "age": 25}';
$data = json_decode($jsonStr, true);
echo $data['name'];  // 输出: 张三

// 解析为对象
$obj = json_decode($jsonStr);
echo $obj->name;

// 从文件读取
$jsonStr = file_get_contents('data.json');
$data = json_decode($jsonStr, true);

生成JSON

<?php
// 将PHP数组转为JSON
$data = ['name' => '张三', 'age' => 25];
$jsonStr = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $jsonStr;

// 写入文件
file_put_contents('output.json', $jsonStr);

// 处理编码错误
if (json_last_error() !== JSON_ERROR_NONE) {
    echo 'JSON编码错误: ' . json_last_error_msg();
}

实用技巧

  • 第二个参数true返回数组,否则返回对象
  • JSON_UNESCAPED_UNICODE保留中文
  • 使用json_last_error()检查错误
💜

C# JSON处理

推荐使用System.Text.Json或Newtonsoft.Json

解析JSON (System.Text.Json)

using System.Text.Json;

// 解析JSON字符串
string json = @"{""name"": ""张三"", ""age"": 25}";
var user = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user.Name);

// 解析为JsonDocument
using JsonDocument doc = JsonDocument.Parse(json);
string name = doc.RootElement.GetProperty("name").GetString();

// 从文件读取
string json = File.ReadAllText("data.json");
var user = JsonSerializer.Deserialize<User>(json);

生成JSON (System.Text.Json)

using System.Text.Json;

// 将对象转为JSON
var user = new User { Name = "张三", Age = 25 };
var options = new JsonSerializerOptions {
    WriteIndented = true,
    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string json = JsonSerializer.Serialize(user, options);

// 写入文件
File.WriteAllText("output.json", json);

实用技巧

  • .NET Core 3.0+推荐System.Text.Json
  • 使用JsonPropertyName自定义字段名
  • 使用JsonSerializerOptions配置序列化

JSON处理常见问题

JSON解析失败怎么办?

首先检查JSON格式是否正确,确保引号、逗号、括号等符合规范。可以使用本工具进行格式验证和一键修复。

如何处理JSON中的特殊字符?

JSON中的双引号、反斜杠、换行符等需要转义。大多数语言的标准库会自动处理转义。

JSON序列化时如何忽略某些字段?

不同语言有不同方式:Python使用default参数,Java使用@JsonIgnore,Go使用json:"-"标签。

如何处理JSON中的日期时间?

JSON没有日期类型,通常使用ISO 8601格式的字符串表示。各语言库通常提供日期序列化配置。

在线JSON格式化工具

验证、格式化、修复您的JSON数据

打开工具