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

如何将filesystem::directory_iterator遍历结果存入nlohmann/json文档

原代码存在的问题

  • 类型不匹配:你声明jComponent为JSON数组类型,但后续使用字符串键"image"、"ini"赋值是JSON对象的操作,运行时会直接报错。
  • 插入位置错误:jComponents是包含Components字段的JSON对象,你直接对它执行push_back操作不会把数据存入目标数组,需要先获取jComponents["Components"]再执行插入。
  • 覆盖问题:如果单个文件夹内存在多个.png或.ini文件,现有写法会反复覆盖同一个键的值,只会保留最后一个匹配的文件路径。
  • 路径序列化问题:直接把std::filesystem::path对象存入JSON,部分版本的nlohmann/json可能无法自动序列化,建议显式转为字符串。
  • 缺少类型判断:没有过滤子目录、软链接等非普通文件条目,可能存入不符合预期的路径。

修正后的实现代码

以下实现默认你预期的JSON结构是:每个子目录对应一个包含image、ini字段的对象,所有对象放在顶层Components数组中。如果需要支持同目录下多份匹配文件,可以自行修改对应字段为数组类型存储。

#include <nlohmann/json.hpp>
#include <filesystem>
#include <string>

namespace fs = std::filesystem;
using json = nlohmann::json;

json scan_component_files(const fs::path& root_path) {
    // 初始化顶层JSON结构,Components为存储结果的数组
    json jComponents = { {"Components", json::array()} };

    // 提前判断根目录合法性,避免运行时报错
    if (!fs::exists(root_path) || !fs::is_directory(root_path)) {
        return jComponents;
    }

    for (const auto& p : fs::directory_iterator(root_path, fs::directory_options::skip_permission_denied)) {
        if (p.is_directory()) {
            // 声明为JSON对象而非数组
            json jComponent = {
                {"image", ""},
                {"ini", ""}
            };
            for (const auto& sub : fs::directory_iterator(p, fs::directory_options::skip_permission_denied)) {
                // 仅处理普通文件
                if (sub.is_regular_file()) {
                    std::string ext = sub.path().extension().string();
                    if (ext == ".png") {
                        // 显式转为字符串,避免序列化兼容问题
                        jComponent["image"] = sub.path().string();
                        // 如需支持多个png,替换为:jComponent["image"].push_back(sub.path().string()); 初始化时image对应设为json::array()即可
                    } else if (ext == ".ini") {
                        jComponent["ini"] = sub.path().string();
                    }
                }
            }
            // 插入到Components数组中
            jComponents["Components"].push_back(jComponent);
        }
    }

    return jComponents;
}

输出结构示例

最终生成的JSON格式如下:

{
  "Components": [
    {
      "image": "test/dir1/cover.png",
      "ini": "test/dir1/config.ini"
    },
    {
      "image": "test/dir2/preview.png",
      "ini": "test/dir2/setting.ini"
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:45:04