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

如何用Python遍历JSON文件并新增指定格式的JSON条目?

问题:使用Python处理游戏JSON配置文件,拆分非空分类下的类型条目

需要处理特定格式的JSON配置文件,用于游戏版本迭代或更新时的维护,具体要求如下:

  • 遍历JSON根层级的所有条目,提取**非空Category**条目下Types数组中的每个数字
  • 为每个提取出的数字创建新条目:Category字段设为空字符串,Types字段为仅包含该数字的数组
  • 将所有新条目追加到JSON的根层级末尾

输入输出示例

输入示例JSON

[
    {
        "Category": "Food",
        "Types": [
            888,
            784654,
            484,
            44841
        ]
    },
    {
        "Category": "",
        "Types": [
            4854
        ]
    }
]

单个新条目格式

{
    "Category": "",
    "Types": [
        888
    ]
}

最终输出示例(完整JSON数组)

[
    {
        "Category": "Food",
        "Types": [
            888,
            784654,
            484,
            44841
        ]
    },
    {
        "Category": "",
        "Types": [
            4854
        ]
    },
    {
        "Category": "",
        "Types": [
            888
        ]
    },
    {
        "Category": "",
        "Types": [
            784654
        ]
    },
    {
        "Category": "",
        "Types": [
            484
        ]
    },
    {
        "Category": "",
        "Types": [
            44841
        ]
    }
]

Python解决方案代码

import json

# 读取输入JSON文件
with open('input.json', 'r', encoding='utf-8') as input_file:
    json_data = json.load(input_file)

new_entries = []

# 遍历原条目,生成新条目
for entry in json_data:
    # 过滤出Category非空的条目(排除空白字符串)
    category = entry.get('Category', '')
    if category.strip():
        # 遍历Types中的每个数字,创建对应新条目
        for type_num in entry['Types']:
            new_entry = {
                "Category": "",
                "Types": [type_num]
            }
            new_entries.append(new_entry)

# 将新条目追加到原数据末尾
json_data.extend(new_entries)

# 写入格式化后的输出JSON文件
with open('output.json', 'w', encoding='utf-8') as output_file:
    json.dump(json_data, output_file, indent=4, ensure_ascii=False)

代码说明

  1. 读取与加载JSON:使用json.load将输入文件内容加载为Python列表,方便后续操作
  2. 过滤与生成新条目:遍历每个原条目,判断Category是否为非空字符串(用strip()避免仅含空格的无效分类),对符合条件的条目,遍历其Types数组生成新条目
  3. 合并与写入:用extend将新条目批量追加到原数据列表,再通过json.dump写入输出文件,indent=4保证输出格式美观,ensure_ascii=False支持中文等非ASCII字符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:15:27