JSON 是列表(List)时如何正确使用?从解析到实战操作指南
在数据交互的世界里,JSON(JavaScript Object Notation)以其轻量、易读、易解析的特性,成为前后端数据传输、配置文件存储、API 响应返回等场景的主流格式,JSON 表示“列表”(即数组)是最常见的形式之一——无论是后端返回的批量数据(如用户列表、商品列表),还是前端存储的有序数据(如待办事项、图表坐标点),都离不开 JSON 列表,本文将从“什么是 JSON 列表”出发,详细讲解如何在不同编程语言中解析、遍历、操作 JSON 列表,并通过实战案例帮助大家其使用方法。
先搞懂:什么是 JSON 列表?
JSON 本质上支持两种结构:对象(Object)和数组(Array)。“JSON 列表”指的就是 JSON 数组,它用方括号 [] 表示,元素之间用逗号 分隔,元素可以是基本数据类型(字符串、数字、布尔值、null),也可以是嵌套的对象或数组。
示例:一个典型的 JSON 列表
[
{ "id": 1, "name": "苹果", "price": 5.8, "in_stock": true },
{ "id": 2, "name": "香蕉", "price": 3.5, "in_stock": false },
{ "id": 3, "name": "橙子", "price": 4.2, "in_stock": true },
[ "促销", "满20减5" ] // 嵌套的数组元素
]
这个 JSON 列表包含 4 个元素:前 3 个是对象(表示商品信息),第 4 个是数组(表示促销标签),可见,JSON 列表的灵活性非常高,可以存储复杂的数据结构。
核心操作:如何解析 JSON 列表?
无论是前端还是后端,使用 JSON 列表的第一步都是将其从“字符串格式”解析为“编程语言原生数据结构”(如 Python 的 list、JavaScript 的 Array、Java 的 List),以下是不同语言的解析方法:
前端:JavaScript/TypeScript
JavaScript 中,JSON 列表的解析主要通过 JSON.parse() 完成。
// 1. 定义 JSON 字符串(模拟从后端接收的响应)
const jsonString = `
[
{ "id": 1, "name": "苹果", "price": 5.8 },
{ "id": 2, "name": "香蕉", "price": 3.5 }
]`;
// 2. 解析为 JavaScript 数组
const productList = JSON.parse(jsonString);
console.log(productList);
// 输出: [ { id: 1, name: '苹果', price: 5.8 }, { id: 2, name: '香蕉', price: 3.5 } ]
// 3. 验证类型
console.log(Array.isArray(productList)); // true
注意:JSON 字符串格式错误(如缺少引号、逗号),JSON.parse() 会抛出 SyntaxError,需用 try-catch 捕获异常:
try {
const invalidJson = "[{ id: 1 }]"; // 缺少 name 的引号
JSON.parse(invalidJson);
} catch (error) {
console.error("JSON 解析失败:", error.message); // 输出: JSON 解析失败: Unexpected token i in JSON at position 3
}
后端:Python
Python 中,使用内置的 json 模块解析 JSON 列表,json.loads() 将字符串转为 list。
import json
# 1. 定义 JSON 字符串(模拟从文件或 API 读取的数据)
json_string = """
[
{ "id": 1, "name": "苹果", "price": 5.8 },
{ "id": 2, "name": "香蕉", "price": 3.5 }
]
"""
# 2. 解析为 Python 列表
product_list = json.loads(json_string)
print(product_list)
# 输出: [{'id': 1, 'name': '苹果', 'price': 5.8}, {'id': 2, 'name': '香蕉', 'price': 3.5}]
# 3. 验证类型
print(isinstance(product_list, list)) # True
进阶:如果希望直接解析 JSON 文件(如 data.json),用 json.load():
with open("data.json", "r", encoding="utf-8") as f:
product_list = json.load(f)
后端:Java
Java 中,常用 Jackson 或 Gson 库解析 JSON 列表(以 Jackson 为例):
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
public class JsonListExample {
public static void main(String[] args) throws Exception {
// 1. 定义 JSON 字符串
String jsonString = """
[
{ "id": 1, "name": "苹果", "price": 5.8 },
{ "id": 2, "name": "香蕉", "price": 3.5 }
]
""";
// 2. 创建 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// 3. 解析为 List<Map>(通用方式)
List<Map<String, Object>> productList = objectMapper.readValue(
jsonString,
new TypeReference<List<Map<String, Object>>>() {}
);
System.out.println(productList);
// 输出: [{id=1, name=苹果, price=5.8}, {id=2, name=香蕉, price=3.5}]
// 4. 解析为自定义 List(推荐,更安全)
class Product {
private int id;
private String name;
private double price;
// getters 和 setters(省略)
}
List<Product> productListObj = objectMapper.readValue(
jsonString,
new TypeReference<List<Product>>() {}
);
System.out.println(productListObj.get(0).getName()); // 输出: 苹果
}
}
进阶操作:遍历、过滤、修改 JSON 列表
解析完成后,对 JSON 列表的遍历、过滤、修改是核心操作,以下继续以 Python 和 JavaScript 为例(两者语法相似,其他语言可类比):
遍历 JSON 列表
JavaScript:
const productList = [
{ id: 1, name: "苹果", price: 5.8 },
{ id: 2, name: "香蕉", price: 3.5 }
];
// 方式1:for 循环
for (let i = 0; i < productList.length; i++) {
console.log(`商品${i + 1}: ${productList[i].name}`);
}
// 方式2:for...of(推荐,更简洁)
for (const product of productList) {
console.log(`商品ID: ${product.id}, 名称: ${product.name}`);
}
// 方式3:forEach(带索引)
productList.forEach((product, index) => {
console.log(`索引${index}: ${product.name},价格: ${product.price}`);
}
Python:
product_list = [
{"id": 1, "name": "苹果", "price": 5.8},
{"id": 2, "name": "香蕉", "price": 3.5}
]
# 方式1:for 循环
for i in range(len(product_list)):
print(f"商品{i + 1}: {product_list[i]['name']}")
# 方式2:for...of(推荐)
for product in product_list:
print(f"商品ID: {product['id']}, 名称: {product['name']}")
# 方式3:enumerate(带索引)
for index, product in enumerate(product_list):
print(f"索引{index}: {product['name']},价格: {product['price']}")
过滤 JSON 列表
假设我们要筛选“价格大于 4 元”的商品:
JavaScript:
const filteredProducts = productList.filter(product => product.price > 4);
console.log(filteredProducts);
// 输出: [ { id: 1, name: '苹果', price: 5.8 } ]
Python:
filtered_products = [product for product in product_list if product["price"] > 4]
print(filtered_products)
# 输出: [{'id': 1, 'name': '苹果', 'price': 5.8}]
修改 JSON 列表
假设我们要给所有商品价格打 9 折:
JavaScript:



还没有评论,来说两句吧...