JSON编程入门指南从零基础到实战应用的完整学习路径与常见问题解析

什么是JSON?
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它基于ECMAScript的一个子集。JSON采用完全独立于语言的文本格式,但同时也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使得JSON成为理想的数据交换语言。
JSON易于人阅读和编写,同时也易于机器解析和生成。它基于两种基本结构:
“名称/值”对的集合
:在不同的语言中,这被实现为对象、记录、结构、字典、哈希表、键控列表或关联数组。
值的有序列表
:在大多数语言中,这被实现为数组。
JSON的基本语法
JSON语法是JavaScript对象表示语法的子集:
数据在名称/值对中
数据由逗号分隔
花括号保存对象
方括号保存数组
JSON名称/值对
JSON数据的书写格式是:名称/值对。
名称/值对包括字段名称(在双引号中)和值,例如:
“firstName”: “John”
JSON对象
JSON对象在花括号中书写,对象可以包含多个名称/值对:
{
“firstName”: “John”,
“lastName”: “Doe”,
“age”: 30,
“address”: {
“streetAddress”: “21 2nd Street”,
“city”: “New York”,
“state”: “NY”,
“postalCode”: “10021”
},
“phoneNumber”: [
{
“type”: “home”,
“number”: “212 555-1234”
},
{
“type”: “office”,
“number”: “646 555-4567”
}
]
}
JSON数组
JSON数组在方括号中书写,数组可包含多个对象:
[
{
“firstName”: “John”,
“lastName”: “Doe”
},
{
“firstName”: “Anna”,
“3
“lastName”: “Smith”
},
{
“firstName”: “Peter”,
“lastName”: “Jones”
}
]
JSON的数据类型
JSON支持以下数据类型:
字符串(String)
:在双引号中,例如 “Hello World”
数字(Number)
:整数或浮点数,例如 42 或 3.14
布尔值(Boolean)
:true 或 false
null
:表示空值
对象(Object)
:用花括号表示,包含键值对
数组(Array)
:用方括号表示,包含值的有序列表
JSON在不同编程语言中的使用
JavaScript中的JSON
JavaScript内置了JSON对象,支持两种主要方法:
1. JSON.parse()
– 将JSON字符串转换为JavaScript对象
// 示例:JSON字符串转换为JavaScript对象
const jsonString = ‘{“name”: “Alice”, “age”: 25, “isStudent”: true}’;
const obj = JSON.parse(jsonString);

console.log(obj.name); // 输出: Alice
console.log(obj.age); // 输出: 25
console.log(obj.isStudent); // 输出: true

// 带有日期的复杂JSON解析
const complexJson = `{
“event”: “Conference”,
“date”: “2023-10-15”,
“attendees”: [“Bob”, “Charlie”, “Diana”],
“location”: {
“name”: “Tech Center”,
“coordinates”: {
“lat”: 40.7128,
“lng”: -74.0060
}
}
}`;

const event = JSON.parse(complexJson);
console.log(`Event: ${event.event}`);
console.log(`First attendee: ${event.attendees[0]}`);
console.log(`Location: ${event.location.name}`);
console.log(`Coordinates: ${event.location.coordinates.lat}, ${event.location.coordinates.lng}`);
2. JSON.stringify()
– 将JavaScript对象转换为JSON字符串
// 示例:JavaScript对象转换为JSON字符串
const person = {
name: “Alice”,
age: 25,
isStudent: true,
hobbies: [“reading”, “coding”, “hiking”]
};

const jsonString = JSON.stringify(person);
console.log(jsonString);
// 输出: {“name”:”Alice”,”age”:25,”isStudent”:true,”hobbies”:[“reading”,”coding”,”hiking”]}

// 带有格式化的输出
const prettyJson = JSON.stringify(person, null, 2);
console.log(prettyJson);
/* 输出:
{
“name”: “Alice”,
“编程入门指南:从零基础到实战应用的完整学习路径与常见问题解析

## 什么是JSON?

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它基于ECMAScript的一个子集。JSON采用完全独立于语言的文本格式,但同时也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使得JSON成为理想的数据交换语言。

JSON易于人阅读和编写,同时也易于机器解析和生成。它基于两种基本结构:
1. **”名称/值”对的集合**:在不同的语言中,这被实现为对象、记录、结构、字典、哈希表、键控列表或关联数组。
2. **值的有序列表**:在大多数语言中,这被实现为数组。

## JSON的基本语法

JSON语法是JavaScript对象表示语法的子集:

– 数据在名称/值对中
– 数据由逗号分隔
– 花括号保存对象
– 方括号保存数组

### JSON名称/值对

JSON数据的书写格式是:名称/值对。
名称/值对包括字段名称(在双引号中)和值,例如:
“`json
“firstName”: “John”
JSON对象
JSON对象在花括号中书写,对象可以包含多个名称/值对:
{
“firstName”: “John”,
“lastName”: “Doe”,
“age”: 30,
“address”: {
“streetAddress”: “21 2nd Street”,
“city”: “New York”,
“state”: “NY”,
“postalCode”: “10021”
},
“phoneNumber”: [
{
“type”: “home”,
“number”: “212 555-1234”
},
{
“type”: “office”,
“number”: “646 555-4567”
}
]
}
JSON数组
JSON数组在方括号中书写,数组可包含多个对象:
[
{
“firstName”: “John”,
“lastName”: “Doe”
},
{
“firstName”: “Anna”,
“lastName”: “Smith”
},
{
“firstName”: “Peter”,
“lastName”: “Jones”
}
]
JSON的数据类型
JSON支持以下数据类型:
字符串(String)
:在双引号中,例如 “Hello World”
数字(Number)
:整数或浮点数,例如 42 或 3.14
布尔值(Boolean)
:true 或 false
null
:表示空值
对象(Object)
:用花括号表示,包含键值对
数组(Array)
:用方括号表示,包含值的有序列表
JSON在不同编程语言中的使用
JavaScript中的JSON
JavaScript内置了JSON对象,支持两种主要方法:
1. JSON.parse()
– 将JSON字符串转换为JavaScript对象
// 示例:JSON字符串转换为JavaScript对象
const jsonString = ‘{“name”: “Alice”, “age”: 25, “isStudent”: true}’;
const obj = JSON.parse(jsonString);

console.log(obj.name); // 输出: Alice
console.log(obj.age); // 输出: 25
console.log(obj.isStudent); // 输出: true

// 带有日期的复杂JSON解析
const complexJson = `{
“event”: “Conference”,
“date”: “2023-10-15”,
“attendees”: [“Bob”, “Charlie”, “Diana”],
“location”: {
“name”: “Tech Center”,
“coordinates”: {
“lat”: 40.7128,
“lng”: -74.0060
}
}
}`;

const event = JSON.parse(complexJson);
console.log(`Event: ${event.event}`);
console.log(`First attendee: ${event.attendees[0]}`);
console.log(`Location: ${event.location.name}`);
console.log(`Coordinates: ${event.location.coordinates.lat}, ${event.location.coordinates.lng}`);
2. JSON.stringify()
– 将JavaScript对象转换为JSON字符串
// 示例:JavaScript对象转换为JSON字符串
const person = {
name: “Alice”,
age: 25,
isStudent: true,
hobbies: [“reading”, “coding”, “hiking”]
};

const jsonString = JSON.stringify(person);
console.log(jsonString);
// 输出: {“name”:”Alice”,”age”:25,”isStudent”:true,”hobbies”:[“reading”,”coding”,”hiking”]}

// 带有格式化的输出
const prettyJson = JSON.stringify(person, null, 2);
console.log(prettyJson);
/* 输出:
{
“name”: “Alice”,
“age”: 25,
“isStudent”: true,
“hobbies”: [
“reading”,
“coding”,
“hiking”
]
}
*/

// 使用replacer函数进行自定义序列化
const user = {
firstName: “John”,
lastName: “Doe”,
password: “secret123”,
email: “john@example.com”
};

const sanitizedJson = JSON.stringify(user, (key, value) => {
if (key === “password”) {
return undefined; // 移除敏感信息
}
return value;
}, 2);

console.log(sanitizedJson);
/* 输出:
{
“firstName”: “John”,
“lastName”: “Doe”,
“email”: “john@example.com”
}
*/
Python中的JSON
Python使用内置的
json
模块处理JSON数据:
import json

# 1. JSON字符串解析为Python字典
json_string = ‘{“name”: “Alice”, “age”: 25, “isStudent”: true, “courses”: [“Math”, “Science”]}’
data = json.loads(json_string)

print(f”Name: {data[‘name’]}”)
print(f”Age: {data[‘age’]}”)
print(f”Courses: {data[‘courses’]}”)

# 2. Python字典转换为JSON字符串
person = {
“name”: “Bob”,
“age”: 30,
“isStudent”: False,
“address”: {
“city”: “Seattle”,
“state”: “WA”
}
}

json_output = json.dumps(person, indent=2)
print(json_output)

# 3. 读写JSON文件
# 写入JSON文件
data_to_save = {
“users”: [
{“id”: 1, “name”: “Alice”, “role”: “admin”},
{“id”: 2, “name”: “Bob”, “role”: “user”}
]
}

with open(‘data.json’, ‘w’) as f:
json.dump(data_to_save, f, indent=2)

# 从JSON文件读取
with open(‘data.json’, ‘r’) as f:
loaded_data = json.load(f)
print(loaded_data)

# 4. 处理中文和其他特殊字符
chinese_data = {
“姓名”: “张三”,
“年龄”: 25,
“城市”: “北京”
}

# ensure_ascii=False 保证中文正常显示
json_chinese = json.dumps(chinese_data, ensure_ascii=False, indent=2)
print(json_chinese)
Java中的JSON
Java处理JSON通常使用第三方库,如Jackson、Gson或org.json:
使用Jackson库:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Map;
import java.util.List;
import java.io.File;

public class JsonExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();

// 1. JSON字符串转换为Java对象
String jsonString = “{\”name\”:\”Alice\”,\”age\”:25,\”isStudent\”:true}”;
Person person = mapper.readValue(jsonString, Person.class);
System.out.println(person.getName());

// 2. JSON字符串转换为Map
String jsonMap = “{\”key1\”:\”value1\”,\”key2\”:\”value2\”}”;
Map map = mapper.readValue(jsonMap, Map.class);
System.out.println(map.get(“key1”));

// 3. Java对象转换为JSON字符串
Person person2 = new Person(“Bob”, 30, false);
String jsonOutput = mapper.writeValueAsString(person2);
System.out.println(jsonOutput);

// 4. 读写JSON文件
// 写入文件
mapper.writeValue(new File(“person.json”), person2);

// 从文件读取
Person fromFile = mapper.readValue(new File(“person.json”), Person.class);
System.out.println(fromFile.getName());

// 5. 处理复杂JSON
String complexJson = “””
{
“users”: [
{“id”: 1, “name”: “Alice”, “roles”: [“admin”, “editor”]},
{“id”: 2, “name”: “Bob”, “roles”: [“viewer”]}
],
“metadata”: {
“total”: 2,
“page”: 1
}
}
“””;

JsonNode root = mapper.readTree(complexJson);
JsonNode users = root.get(“users”);
for (JsonNode user : users) {
System.out.println(“User: ” + user.get(“name”).asText());
}
}
}

// Person类定义
class Person {
private String name;
private int age;
private boolean isStudent;

// 无参构造函数(Jackson需要)
public Person() {}

public Person(String name, int age, boolean isStudent) {
this.name = name;
this.age = age;
this.isStudent = isStudent;
}

// getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public boolean isStudent() { return isStudent; }
public void setStudent(boolean student) { isStudent = student; }
}
JSON实战应用场景
1. Web API数据交换
JSON是现代Web API的标准数据格式。以下是一个完整的REST API示例:
前端JavaScript调用API:
// 使用fetch API获取JSON数据
async function fetchUserData() {
try {
const response = await fetch(‘https://api.example.com/users/123’);
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
const userData = await response.json();

// 处理用户数据
displayUser(userData);
} catch (error) {
console.error(‘Error fetching user data:’, error);
}
}

function displayUser(user) {
const userInfo = `

${user.name}

Email: ${user.email}

Role: ${user.role}

Last Login: ${new Date(user.lastLogin).toLocaleString()}

`;
document.getElementById(‘user-container’).innerHTML = userInfo;
}

// 提交JSON数据到服务器
async function createUser(userData) {
const response = await fetch(‘https://api.example.com/users’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: ‘Bearer your-token-here’
},
body: JSON.stringify(userData)
});

if (response.ok) {
const result = await response.json();
console.log(‘User created:’, result);
return result;
} else {
throw new Error(‘Failed to create user’);
}
}

// 使用示例
const newUser = {
name: “Alice Johnson”,
email: “alice@example.com”,
role: “developer”,
preferences: {
theme: “dark”,
notifications: true
}
};

createUser(newUser);
后端Node.js/Express处理JSON:
const express = require(‘express’);
const app = express();

// 中间件:解析JSON请求体
app.use(express.json());

// GET端点 – 返回JSON数据
app.get(‘/api/users/:id’, (req, res) => {
const userId = req.params.id;

// 模拟数据库查询
const user = {
id: userId,
name: “Alice Johnson”,
email: “alice@example.com”,
role: “developer”,
lastLogin: new Date().toISOString(),
preferences: {
theme: “dark”,
notifications: true
}
};

res.json(user);
});

// POST端点 – 接收JSON数据
app.post(‘/api/users’, (req, res) => {
const userData = req.body;

// 数据验证
if (!userData.name || !userData.email) {
return res.status(400).json({
error: “Name and email are required”
});
}

// 处理数据(保存到数据库等)
const newUser = {
id: Date.now().toString(),
…userData,
createdAt: new Date().toISOString()
};

res.status(201).json(newUser);
});

// PUT端点 – 更新JSON数据
app.put(‘/api/users/:id’, (req, res) => {
const userId = req.params.id;
const updates = req.body;

// 模拟更新操作
const updatedUser = {
id: userId,
…updates,
updatedAt: new Date().toISOString()
};

res.json(updatedUser);
});

app.listen(3000, () => {
console.log(‘Server running on port 3000’);
});
2. 配置文件管理
JSON常用于应用程序配置:
config.json:
{
“database”: {
“host”: “localhost”,
“port”: 5432,
“name”: “myapp”,
“user”: “admin”,
“password”: “secret”
},
“server”: {
“port”: 3000,
“host”: “0.0.0.0”,
“ssl”: false
},
“logging”: {
“level”: “info”,
“file”: “app.log”,
“console”: true
},
“features”: {
“enableCache”: true,
“maxConnections”: 100,
“timeout”: 5000
}
}
加载配置的JavaScript代码:
const fs = require(‘fs’);

class Config {
constructor(configPath = ‘./config.json’) {
this.config = this.loadConfig(configPath);
}

loadConfig(path) {
try {
const data = fs.readFileSync(path, ‘utf8’);
return JSON.parse(data);
} catch (error) {
console.error(‘Error loading config:’, error);
// 返回默认配置
return this.getDefaultConfig();
}
}

getDefaultConfig() {
return {
database: { host: ‘localhost’, port: 5432 },
server: { port: 3000 },
logging: { level: ‘info’ }
};
}

getDatabaseConfig() {
return this.config.database;
}

getServerConfig() {
return this.config.server;
}

// 更新配置并保存
updateConfig(key, value) {
// 使用lodash的set或类似功能
this.setNestedValue(this.config, key, value);
this.saveConfig();
}

setNestedValue(obj, path, value) {
const keys = path.split(‘.’);
let current = obj;

for (let i = 0; i < keys.length - 1; i++) { if (!current[keys[i]]) { current[keys[i]] = {}; } current = current[keys[i]]; } current[keys[keys.length - 1]] = value; } saveConfig() { try { fs.writeFileSync('./config.json', JSON.stringify(this.config, null, 2)); console.log('Configuration saved successfully'); } catch (error) { console.error('Error saving config:', error); } } } // 使用示例 const config = new Config(); console.log('Database host:', config.getDatabaseConfig().host); // 更新配置 config.updateConfig('server.port', 8080); 3. 数据存储和缓存 JSON可用于本地数据存储: 浏览器端使用localStorage: // 保存数据到localStorage function saveToLocalStorage(key, data) { try { const jsonString = JSON.stringify(data); localStorage.setItem(key, jsonString); return true; } catch (error) { console.error('Error saving to localStorage:', error); return false; } } // 从localStorage读取数据 function loadFromLocalStorage(key) { try { const jsonString = localStorage.getItem(key); if (jsonString === null) { return null; } return JSON.parse(jsonString); } catch (error) { console.error('Error loading from localStorage:', error); return null; } } // 使用示例:保存用户偏好设置 const userPreferences = { theme: 'dark', fontSize: 14, language: 'en', notifications: { email: true, push: false, sms: true } }; saveToLocalStorage('userPreferences', userPreferences); // 读取并修改 const savedPrefs = loadFromLocalStorage('userPreferences'); if (savedPrefs) { savedPrefs.theme = 'light'; saveToLocalStorage('userPreferences', savedPrefs); } Node.js文件系统存储: const fs = require('fs').promises; const path = require('path'); class JsonDatabase { constructor(filePath) { this.filePath = filePath; this.initialize(); } async initialize() { try { await fs.access(this.filePath); } catch { // 文件不存在,创建空数据库 await fs.writeFile(this.filePath, JSON.stringify({ users: [] }, null, 2)); } } async readData() { try { const data = await fs.readFile(this.filePath, 'utf8'); return JSON.parse(data); } catch (error) { console.error('Error reading database:', error); return { users: [] }; } } async writeData(data) { try { await fs.writeFile(this.filePath, JSON.stringify(data, null, 2)); return true; } catch (error) { console.error('Error writing database:', error); return false; } } async addUser(user) { const data = await this.readData(); const newUser = { id: Date.now().toString(), ...user, createdAt: new Date().toISOString() }; data.users.push(newUser); await this.writeData(data); return newUser; } async findUserById(id) { const data = await this.readData(); return data.users.find(user => user.id === id);
}

async updateUser(id, updates) {
const data = await this.readData();
const index = data.users.findIndex(user => user.id === id);
if (index !== -1) {
data.users[index] = { …data.users[index], …updates };
await this.writeData(data);
return data.users[index];
}
return null;
}

async deleteUser(id) {
const data = await this.readData();
const index = data.users.findIndex(user => user.id === id);
if (index !== -1) {
data.users.splice(index, 1);
await this.writeData(data);
return true;
}
return false;
}
}

// 使用示例
async function demo() {
const db = new JsonDatabase(‘./users.json’);

// 添加用户
const user1 = await db.addUser({
name: “Alice”,
email: “alice@example.com”
});
console.log(‘Added user:’, user1);

// 查找用户
const found = await db.findUserById(user1.id);
console.log(‘Found user:’, found);

// 更新用户
const updated = await db.updateUser(user1.id, { name: “Alice Smith” });
console.log(‘Updated user:’, updated);

// 删除用户
const deleted = await db.deleteUser(user1.id);
console.log(‘Deleted:’, deleted);
}

demo();
4. 日志记录和调试
JSON格式的日志便于分析和处理:
// JSON格式日志记录器
class JsonLogger {
constructor() {
this.logs = [];
}

log(level, message, metadata = {}) {
const logEntry = {
timestamp: new Date().toISOString(),
level: level,
message: message,
…metadata
};

this.logs.push(logEntry);

// 同时输出到控制台
console.log(JSON.stringify(logEntry));

// 可以扩展为写入文件或发送到日志服务
}

info(message, metadata = {}) {
this.log(‘INFO’, message, metadata);
}

error(message, metadata = {}) {
this.log(‘ERROR’, message, metadata);
}

warn(message, metadata = {}) {
this.log(‘WARN’, message, metadata);
}

// 获取特定时间段的日志
getLogs(from, to) {
return this.logs.filter(log => {
const logTime = new Date(log.timestamp);
return logTime >= from && logTime <= to; }); } // 导出日志为JSON文件 exportLogs(filename) { const fs = require('fs'); const data = JSON.stringify(this.logs, null, 2); fs.writeFileSync(filename, data); console.log(`Logs exported to ${filename}`); } } // 使用示例 const logger = new JsonLogger(); logger.info('User login attempt', { userId: '123', ip: '192.168.1.1' }); logger.error('Database connection failed', { error: 'Connection timeout', attempts: 3, lastError: 'ETIMEDOUT' }); logger.warn('High memory usage detected', { memory: { used: 85, total: 100 }, process: 'node-app' }); // 模拟一些操作后导出日志 setTimeout(() => {
logger.exportLogs(‘app-logs.json’);
}, 1000);
JSON常见问题解析
1. JSON解析错误
问题:
SyntaxError: Unexpected token x in JSON at position y
原因:
JSON格式不正确,常见问题包括:
使用单引号而不是双引号
末尾多余的逗号
未转义的特殊字符
不合法的数字格式
解决方案:
// ❌ 错误示例
const invalidJson1 = ‘{“name”: “Alice”,}’; // 末尾逗号
const invalidJson2 = “{‘name’: ‘Alice’}”; // 单引号
const invalidJson3 = ‘{“name”: “Alice” }’; // 未转义的换行符

// ✅ 正确示例
const validJson = ‘{“name”: “Alice”}’;

// 验证JSON格式的函数
function isValidJson(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}

// 安全的JSON解析
function safeJsonParse(str, defaultValue = null) {
try {
return JSON.parse(str);
} catch (error) {
console.error(‘JSON Parse Error:’, error.message);
return defaultValue;
}
}

// 使用示例
const result = safeJsonParse(‘{“invalid”: }’, { fallback: true });
console.log(result); // { fallback: true }
2. 循环引用问题
问题:
TypeError: Converting circular structure to JSON
原因:
对象相互引用,形成循环,导致JSON.stringify()失败
解决方案:
// ❌ 问题示例
const obj1 = { name: “Alice” };
const obj2 = { name: “Bob” };
obj1.friend = obj2;
obj2.friend = obj1; // 循环引用

// JSON.stringify(obj1); // 报错!

// ✅ 解决方案1:使用replacer函数过滤循环引用
function getCircularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === “object” && value !== null) {
if (seen.has(value)) {
return; // 移除循环引用
}
seen.add(value);
}
return value;
};
}

const safeString = JSON.stringify(obj1, getCircularReplacer(), 2);
console.log(safeString);

// ✅ 解决方案2:自定义序列化函数
function serializeWithoutCircular(obj, seen = new WeakSet()) {
if (obj === null || typeof obj !== ‘object’) {
return obj;
}

if (seen.has(obj)) {
return ‘[Circular]’;
}

seen.add(obj);

if (Array.isArray(obj)) {
return obj.map(item => serializeWithoutCircular(item, seen));
}

const result = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = serializeWithoutCircular(obj[key], seen);
}
}

return result;
}

const circularSafe = serializeWithoutCircular(obj1);
console.log(JSON.stringify(circularSafe, null, 2));
3. 大数据量处理
问题:
处理大型JSON文件时内存溢出
解决方案:
const fs = require(‘fs’);
const JSONStream = require(‘jsonstream’); // 需要安装: npm install jsonstream

// ❌ 错误做法:一次性读取大文件
function processLargeJsonFileWrong(filePath) {
const data = fs.readFileSync(filePath, ‘utf8’); // 内存爆炸!
const json = JSON.parse(data);
// 处理数据…
}

// ✅ 正确做法:使用流式处理
function processLargeJsonFileCorrect(filePath) {
const stream = fs.createReadStream(filePath, { encoding: ‘utf8’ });
const parser = JSONStream.parse(‘users.*’); // 解析users数组中的每个对象

stream.pipe(parser);

parser.on(‘data’, (user) => {
// 逐个处理用户对象
console.log(‘Processing user:’, user.id);
// 处理逻辑…
});

parser.on(‘error’, (error) => {
console.error(‘Stream error:’, error);
});

parser.on(‘end’, () => {
console.log(‘Processing complete’);
});
}

// 手动流式解析(不使用第三方库)
function streamJsonManually(filePath) {
const stream = fs.createReadStream(filePath, { encoding: ‘utf8’ });
let buffer = ”;
let depth = 0;
let inString = false;
let escape = false;

stream.on(‘data’, (chunk) => {
buffer += chunk;

// 简单的逐字符解析(实际应用中应使用更复杂的逻辑)
for (let i = 0; i < buffer.length; i++) { const char = buffer[i]; if (escape) { escape = false; continue; } if (char === '\\') { escape = true; continue; } if (char === '"') { inString = !inString; continue; } if (!inString) { if (char === '{') depth++; else if (char === '}') { depth--; if (depth === 0) { // 找到一个完整的对象 const objStr = buffer.substring(0, i + 1); try { const obj = JSON.parse(objStr); console.log('Parsed object:', obj); } catch (e) { // 处理不完整对象 } buffer = buffer.substring(i + 1); i = -1; // 重置循环 } } } } }); } 4. 安全问题 问题: JSON注入攻击 解决方案: // ❌ 不安全的做法 function unsafeDisplayUserData(userInput) { // 直接将用户输入拼接成JSON const jsonStr = `{"username": "${userInput}"}`; const data = JSON.parse(jsonStr); document.getElementById('output').innerHTML = data.username; } // ✅ 安全的做法 function safeDisplayUserData(userInput) { // 1. 验证输入 if (typeof userInput !== 'string') { throw new Error('Invalid input type'); } // 2. 转义特殊字符 const escaped = userInput .replace(/&/g, '&') .replace(//g, ‘>’)
.replace(/”/g, ‘"’)
.replace(/’/g, ‘'’);

// 3. 创建安全的JSON对象
const safeData = {
username: escaped
};

// 4. 使用textContent而不是innerHTML
document.getElementById(‘output’).textContent = safeData.username;
}

// 安全的JSON序列化(防止原型污染)
function safeStringify(obj) {
// 过滤掉原型属性
const seen = new WeakSet();

return JSON.stringify(obj, (key, value) => {
if (typeof value === ‘object’ && value !== null) {
if (seen.has(value)) {
return undefined;
}
seen.add(value);

// 检查原型污染
if (key === ‘__proto__’ || key === ‘constructor’ || key === ‘prototype’) {
return undefined;
}
}
return value;
});
}

// 使用示例
const user = {
name: “Alice”,
data: {
__proto__: { polluted: true }, // 尝试原型污染
normal: “value”
}
};

console.log(safeStringify(user));
// 输出: {“name”:”Alice”,”data”:{“normal”:”value”}}
5. 性能优化技巧
// 1. 缓存解析结果
const parseCache = new Map();
function cachedJsonParse(str) {
if (parseCache.has(str)) {
return parseCache.get(str);
}
const result = JSON.parse(str);
parseCache.set(str, result);
return result;
}

// 2. 使用JSON.parse的reviver进行预处理
function parseWithReviver(jsonStr) {
const reviver = (key, value) => {
// 自动转换日期字符串为Date对象
if (typeof value === ‘string’ && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
// 自动转换数字字符串为数字
if (typeof value === ‘string’ && !isNaN(value) && value.trim() !== ”) {
return Number(value);
}
return value;
};

return JSON.parse(jsonStr, reviver);
}

// 3. 选择性序列化
function selectiveStringify(obj, keysToInclude) {
const filtered = {};
keysToInclude.forEach(key => {
if (key in obj) {
filtered[key] = obj[key];
}
});
return JSON.stringify(filtered);
}

// 使用示例
const fullUser = {
id: 1,
name: “Alice”,
password: “secret”,
email: “alice@example.com”,
internalId: “INT-123”
};

const publicUser = selectiveStringify(fullUser, [‘id’, ‘name’, ’email’]);
console.log(publicUser);
// 输出: {“id”:1,”name”:”Alice”,”email”:”alice@example.com”}
JSON学习路径建议
第一阶段:基础语法(1-2天)
理解JSON的基本结构
掌握数据类型
练习手写JSON
使用在线验证工具(如JSONLint)
第二阶段:编程语言集成(3-5天)
JavaScript:掌握parse/stringify
Python:学习json模块
Java:熟悉Jackson或Gson
练习不同语言间的JSON转换
第三阶段:实战应用(1-2周)
构建REST API
处理配置文件
实现数据持久化
调试JSON相关问题
第四阶段:高级主题(持续学习)
JSON Schema验证
JSONPath查询
性能优化
安全最佳实践
总结
JSON作为一种轻量级的数据交换格式,在现代软件开发中扮演着至关重要的角色。从简单的配置文件到复杂的API数据交换,JSON的应用无处不在。掌握JSON不仅需要理解其基本语法,还需要了解在不同编程语言中的最佳实践、常见问题的解决方案以及性能优化技巧。
通过本文的学习,您应该能够:
理解JSON的基本概念和语法规则
在主流编程语言中使用JSON
构建实际的JSON应用
解决常见的JSON问题
应用性能优化和安全最佳实践
继续实践和探索JSON的更多高级特性,将帮助您在软件开发中更加游刃有余。