You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python宝可梦数据爬虫中正确格式化JSON输出

解决方案

针对你遇到的两个JSON格式化问题,分两步解决:

1. 将moves_list从嵌套列表改为字典列表

你当前的moves_list是列表嵌套列表,要改成示例中的字典结构,需要在采集招式数据时直接构建字典:

# 替换你原来生成moves_list的代码
moves_list = []
# 假设你遍历每个招式元素的循环是这样的
for move_item in scraped_move_elements:
    # 从页面提取对应字段(替换成你实际的采集逻辑)
    move_name = move_item.find('td', class_='move-name').text.strip()
    move_type = move_item.find('td', class_='move-type').text.strip()
    move_cat = move_item.find('td', class_='move-category').text.strip()
    move_power = move_item.find('td', class_='move-power').text.strip()
    move_accuracy = move_item.find('td', class_='move-accuracy').text.strip()
    
    # 构建招式字典
    move_dict = {
        "move_name": move_name,
        "move_type": move_type,
        "move_cat": move_cat,
        "move_power": move_power,
        "move_accuracy": move_accuracy
    }
    moves_list.append(move_dict)

2. 实现短列表的单行格式化输出

Python标准库的json.dump默认会把列表元素换行显示,要让短列表(如types、abilities)单行显示,需要自定义JSON编码器:

import json

class CompactListJSONEncoder(json.JSONEncoder):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.indent = kwargs.get('indent', 4)
        self.compact_short_lists = kwargs.pop('compact_short_lists', True)

    def encode(self, obj):
        # 处理字符串类型的短列表(长度≤5)
        if isinstance(obj, list) and self.compact_short_lists:
            if all(isinstance(item, str) for item in obj) and len(obj) <= 5:
                return f'[{", ".join(json.dumps(item) for item in obj)}]'
            # 处理招式字典列表,单行显示
            elif all(isinstance(item, dict) for item in obj):
                return f'[{", ".join(self.encode(item) for item in obj)}]'
        # 其他类型按默认逻辑处理
        return super().encode(obj)

写入JSON文件时使用自定义编码器

# 假设你的最终数据存在data变量中
with open('pokemon_data.json', 'w', encoding='utf-8') as json_file:
    json.dump(
        data,
        json_file,
        cls=CompactListJSONEncoder,
        indent=4,
        ensure_ascii=False,
        compact_short_lists=True
    )

这样输出的JSON就会符合你的需求:短字符串列表单行显示,moves_list变成字典嵌套结构。

内容的提问来源于stack exchange,提问作者Emir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:28:02