如何将路径数组转换为JSON结构?

时间:2016-03-27 14:07:07

标签: javascript json javascript-objects

我发现了问题How to convert a file path into treeview?,但我不确定如何在JavaScript中获得所需的结果:

我正在尝试将一组路径转换为JSON树:

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

但是我的道路被覆盖了。

我想尝试这样的事情:

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

......然后把它变成......

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

我确信这很容易,但我错过了一些东西。

3 个答案:

答案 0 :(得分:6)

这是我写的解决方案:

var 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"
];

var output = {};
var current;

for(var a=0; a<data.length; a++) {
  var s = data[a].split('/');
  current = output;
  for(var i=0; i<s.length; i++) {
    if(s[i] != '') {
      if(current[s[i]] == null) current[s[i]] = {};
      current = current[s[i]];
    }
  }
}

console.log(output);

它将完成你需要的一切,并且紧凑。但是,对于解决方案中的问题,它与您管理current的方式有关。具体来说,你有这个:

current = output[path[0]];

而不是:

current = output;

这意味着初始化output的代码每次都会运行,因为path[0]在您的数据中始终为'',而output['']不会

答案 1 :(得分:3)

此功能应该:

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;
}

演示

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>';

(另见this Fiddle

答案 2 :(得分:0)

注意:生成的数组需要合并

此方法适用于文件和文件。目录,并仅使用数组作为数据格式。

结构基于数组是文件夹,第一个元素是文件夹名称,第二个元素是内容数组。

文件只是数组中的常规字符串(但很容易就是包含属性的对象)

转换=&gt;

[
  '/home/',
  '/home/user/.bashrc',
  '/var/',
  '/var/test.conf',
  '/var/www/',
  '/var/www/index.html',
  '/var/www/index2.html'
]

To =&gt;

[
  ['home', [
    ['user', [
      '.bashrc'
    ]]
  ]],
  ['var', [
    'test.conf',
    ['www', [
      'index.html',
      'index2.html'
    ]]
  ]]
]

<强>脚本:

var paths = [
  '/var/',
  '/var/test.conf',
  '/var/www/',
  '/var/www/index.html',
  '/var/www/index2.html'
]

var parsed = []

for (let path of paths) {
  let tree = path.split('/')
  let previous = parsed

  console.groupCollapsed(path)
  for (let item in tree) {
    const name = tree[item]
    const last = item == tree.length - 1

    if (name) {
      if (last) {
        console.log('File:', name)
        previous.push(name) - 1
      } else {
        console.log('Folder:', name)
        let i = previous.push([name, []]) - 1
        previous = previous[i][1]
      }  
    }
  }
  console.groupEnd(path)
}

console.warn(JSON.stringify(parsed))