Skip to content

Question about making json object from file directory #1449

Closed
@shanekoss

Description

I'm attempting to scan a folder and its subfolders to make a json object of the entire directory. So far I have this:

struct json_node;
using json_node_ptr = std::shared_ptr<json_node>;

struct json_node
{
    std::string id;
    std::vector<json_node_ptr> children;
    
    json_node(std::string _id)
    : id{ _id }
    {
    }
};

void to_json(nlohmann::json& j, const json_node_ptr& node)
{
    j = {{node->id, node->children}};
}

int main (int argc, char* argv[])
{
    std::vector<std::string> values = {"Folder 1","Folder 2","Folder 3","Folder 4","fileInFolder"};
    std::vector<json_node_ptr> parents;
    
    for(int i = 0; i < values.size(); i++)
    {
        if ( i == 0 ) {
            auto root = std::make_shared<json_node>(values[0]);
            parents.push_back(root);
        } else {
            parents.push_back(std::make_shared<json_node>(values[i]));
            parents[i-1]->children.push_back(parents[i]);
        }
    }
  
    nlohmann::json j = parents[0];
    std::cout << j.dump(2) << std::endl;
    
    
    return 0;
}

which works somewhat - it returns this:

{ "Folder 1": [ { "Folder 2": [ { "Folder 3": [ { "Folder 4": [ { "fileInFolder": [] } ] } ] } ] } ] }

and i'd like to have the last item as a string in the array - not another object - like so:

{ "Folder 1": [ { "Folder 2": [ { "Folder 3": [ { "Folder 4": [ "fileInFolder" ] } ] } ] } ] }

More importantly - not sure how to adapt this to handle multiple files (vectors) in the directory - (not just the single vector I have here) so that all files and folders are represented correctly in the object. Any pointers would be appreciated!

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions