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

ldfqzlk8  于 2022-12-15  发布在  其他
关注(0)|答案(3)|浏览(171)

我找到了问题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: {}
     }
   }
}

我知道这很简单,但我漏掉了什么。

qnyhuwrf

qnyhuwrf1#

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

你的解决方案很接近,只是没有正确地重置current变量。

current = output;

而不是这样:

current = output[path[0]];
cuxqih21

cuxqih212#

此函数应执行以下操作:

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

(see也称为this Fiddle

q8l4jmvw

q8l4jmvw3#

注意:需要合并生成的数组
这个方法对文件和目录都有效,并且只使用数组作为数据格式。
该结构基于文件夹数组,第一个元素是文件夹名称,第二个元素是内容数组。
文件只是数组中的常规字符串(但也可以是包含属性的对象)

转化率=〉

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

至=〉

[
  ['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))

相关问题