Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of paths into JSON structure?

I found the question How to convert a file path into treeview?, but I'm not sure how to get the desired result in JavaScript:

I'm trying to turn an array of paths into a JSON tree:

https://jsfiddle.net/tfkdagzv/16/

But my path is being overwritten.

I'm trying to take something like this:

[
    '/org/openbmc/path1', 
    '/org/openbmc/path2', 
    ...
]

... and turn it into...

output = {
   org: {
     openbmc: {
       path1: {},
       path2: {}
     }
   }
}

I'm sure this is pretty easy, but I'm missing something.

like image 445
Lindsay Avatar asked Mar 27 '16 14:03

Lindsay


People also ask

How do I convert an array to JSON?

JS Array to JSON using JSON.const jsonString = JSON. stringify([1, 2, 3, 4, 5]); The JSON. stringify() method converts a JavaScript object, array, or value to a JSON string.

What is the difference between {} and [] in JSON?

{} denote containers, [] denote arrays.

Can you save array as JSON?

JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.

Can you JSON Stringify an array?

It is also possible to stringify JavaScript arrays: Imagine we have this array in JavaScript: const arr = ["John", "Peter", "Sally", "Jane"]; Use the JavaScript function JSON.stringify() to convert it into a string.


2 Answers

const data = [
    "/org/openbmc/examples/path0/PythonObj",
    "/org/openbmc/UserManager/Group",
    "/org/openbmc/HostIpmi/1",
    "/org/openbmc/HostServices",
    "/org/openbmc/UserManager/Users",
    "/org/openbmc/records/events",
    "/org/openbmc/examples/path1/SDBusObj",
    "/org/openbmc/UserManager/User",
    "/org/openbmc/examples/path0/SDBusObj",
    "/org/openbmc/examples/path1/PythonObj",
    "/org/openbmc/UserManager/Groups",
    "/org/openbmc/NetworkManager/Interface"
];

const output = {};
let current;

for (const path of data) {
    current = output;

    for (const segment of path.split('/')) {
        if (segment !== '') {
            if (!(segment in current)) {
                current[segment] = {};
            }

            current = current[segment];
        }
    }
}

console.log(output);

Your solution was close, you just didn't reset the current variable properly. Use this:

current = output;

instead of this:

current = output[path[0]];
like image 68
Sabumnim Avatar answered Sep 29 '22 03:09

Sabumnim


This function should do :

var parsePathArray = function() {
    var parsed = {};
    for(var i = 0; i < paths.length; i++) {
        var position = parsed;
        var split = paths[i].split('/');
        for(var j = 0; j < split.length; j++) {
            if(split[j] !== "") {
                if(typeof position[split[j]] === 'undefined')
                    position[split[j]] = {};
                position = position[split[j]];
            }
        }
    }
    return parsed;
}

Demo

var paths = [
    "/org/openbmc/UserManager/Group",
    "/org/stackExchange/StackOverflow",
    "/org/stackExchange/StackOverflow/Meta",
    "/org/stackExchange/Programmers",
    "/org/stackExchange/Philosophy",
    "/org/stackExchange/Religion/Christianity",
    "/org/openbmc/records/events",
    "/org/stackExchange/Religion/Hinduism",
    "/org/openbmc/HostServices",
    "/org/openbmc/UserManager/Users",
    "/org/openbmc/records/transactions",
    "/org/stackExchange/Religion/Islam",
    "/org/openbmc/UserManager/Groups",
    "/org/openbmc/NetworkManager/Interface"
];

var parsePathArray = function() {
    var parsed = {};
    for(var i = 0; i < paths.length; i++) {
        var position = parsed;
        var split = paths[i].split('/');
        for(var j = 0; j < split.length; j++) {
            if(split[j] !== "") {
                if(typeof position[split[j]] === 'undefined')
                    position[split[j]] = {};
                position = position[split[j]];
            }
        }
    }
    return parsed;
}

document.body.innerHTML = '<pre>' +
                          JSON.stringify(parsePathArray(), null, '\t')
                          '</pre>';

(see also this Fiddle)

like image 33
John Slegers Avatar answered Sep 29 '22 03:09

John Slegers