JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,同时也易于解析和生成。JSON 格式主要用于在前后端之间传输数据。
- 基本结构JSON 数据格式包括对象和数组:
示例:
{
"name": "Alice",
"age": 30,
"isStudent": false,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"profile": null
}
-
- 对象:由
{}
包围,内部包含键值对。键(属性名)必须是字符串,值可以是字符串、数字、布尔值、对象、数组或null
。 - 数组:由
[]
包围,内部可以包含任意类型的值,包括对象和其他数组。
- 对象:由
- JSON 数据类型
-
- 字符串:用双引号包围(例如
"Hello World"
)。 - 数字:没有引号(例如
123
,45.67
)。 - 布尔值:
true
或false
。 - 对象:用花括号包围(例如
{"key": "value"}
)。 - 数组:用方括号包围(例如
[1, 2, 3]
)。 - null:表示空值(例如
null
)。
- 字符串:用双引号包围(例如
前端使用 JSON
- 解析 JSON 数据在前端 JavaScript 中,可以使用
JSON.parse()
将 JSON 字符串转换为 JavaScript 对象:
let jsonString = '{"name": "Alice", "age": 30}';
let obj = JSON.parse(jsonString);
console.log(obj.name); // 输出: Alice
- 生成 JSON 数据使用
JSON.stringify()
将 JavaScript 对象转换为 JSON 字符串:
let person = {
name: 'Bob',
age: 25
};
let jsonString = JSON.stringify(person);
console.log(jsonString); // 输出: {"name":"Bob","age":25}
- 在前端与后端交互时使用 JSON当通过 HTTP 请求与后端交互时,JSON 是一种常用的数据格式。可以使用
fetch
或XMLHttpRequest
来发送和接收 JSON 数据:
// 发送 JSON 数据到服务器
fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Charlie',
age: 40
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// 从服务器获取 JSON 数据
fetch('https://example.com/api')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
后端使用 JSON
- 接收 JSON 数据后端可以接收并解析 JSON 数据,这取决于使用的编程语言和框架。例如,在 Node.js 中,可以使用 Express 框架来处理 JSON 请求:
const express = require('express');
const app = express();
app.use(express.json()); // 中间件,用于解析 JSON 请求体
app.post('/api', (req, res) => {
console.log(req.body); // req.body 是解析后的 JSON 对象
res.send('Received JSON data');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
- 返回 JSON 数据后端可以将数据作为 JSON 响应返回。例如,在 Node.js 中使用 Express:
app.get('/api', (req, res) => {
res.json({
name: 'David',
age: 50
});
});
总结
- JSON 格式通过键值对的方式表示数据,支持多种数据类型。
- 在前端,使用
JSON.parse()
和JSON.stringify()
来处理 JSON 数据。 - 在前后端交互中,JSON 是一种广泛使用的数据格式。
- 后端根据不同的编程语言和框架解析和生成 JSON 数据。