
基本的 JSON 解析
- 
当从淘宝 API 接口获取到数据后(假设数据存储在变量
response_data中),首先要判断数据类型是否为 JSON。如果是,就可以使用 Python 内置的json模块进行解析。 - 
示例代码如下:
import json # 假设response_data是从淘宝API获取到的数据 try: json_data = json.loads(response_data) print(json_data) except json.JSONDecodeError as e: print("数据不是有效的JSON格式,错误:", e) - 
这里的
json.loads()函数用于将 JSON 格式的字符串转换为 Python 的数据结构(如字典、列表等)。 - 
访问 JSON 数据中的特定字段
- 
一旦将 JSON 数据转换为 Python 数据结构,就可以像访问普通 Python 字典或列表一样访问其中的字段。
 - 
例如,如果淘宝 API 返回的 JSON 数据包含商品信息,其中商品名称存储在
product_name字段,价格存储在price字段,代码如下:if isinstance(json_data, dict):
product_name = json_data.get("product_name")
price = json_data.get("price")
print("商品名称:", product_name)
print("商品价格:", price) 
 - 
 - 
这里使用
get()方法从字典中获取值,这样如果键不存在,不会引发KeyError,而是返回None。 
- 处理嵌套的 JSON 结构
- 
淘宝 API 返回的数据可能有复杂的嵌套结构。例如,商品详情可能包含一个卖家信息的子结构。
 - 
假设卖家信息存储在
seller子字段中,包括卖家名称seller_name和卖家评分seller_rating,代码如下:if "seller" in json_data: seller_info = json_data["seller"] seller_name = seller_info.get("seller_name") seller_rating = seller_info.get("seller_rating") print("卖家名称:", seller_name) print("卖家评分:", seller_rating)使用循环处理 JSON 数组(如果有)
 - 
有时候,API 返回的数据可能包含一个数组,例如,返回多个商品评论的信息。
 - 
假设
comments是一个包含商品评论的数组,每个评论包含评论内容content和评论者名称commenter_name,代码如下:if "comments" in json_data and isinstance(json_data["comments"], list): for comment in json_data["comments"]: content = comment.get("content") commenter_name = comment.get("commenter_name") print("评论内容:", content) print("评论者名称:", commenter_name)这样就可以遍历数组中的每个元素(评论),并获取和打印相关信息。
 
 -