Json的字符串路径

时间:2018-08-01 00:59:39

标签: javascript jquery json parsing

我有如下所示的路径列表。

var paths = [
    "ubx/ubx-producao/Editora Abril/Exame 1106/FINANCAS_INOCAVAO_STARTUP_BANCOES.mp3",
    "ubx/ubx-producao/Editora Alto Astral/Previsoes signos Fevereiro 2016/aquario-fevereiro.mp3",
    "ubx/ubx-producao/Editora Alto Astral/Previsoes signos Fevereiro 2016/aries-fevereiro.mp3"];

我使用下面的代码解析为JSON。

let treePath = { };

paths.forEach(path => {
    let levels = path.split("/");
    let file = levels.pop() 
    let prevLevel = treePath;
    let prevProp = levels.shift()   

    levels.forEach(prop => {
        prevLevel[prevProp] = prevLevel[prevProp] || {};
        prevLevel = prevLevel[prevProp];
        prevProp = prop
    });
    prevLevel[prevProp] = (prevLevel[prevProp] || []).concat([file]);
});

我得到的结果如下所示: output result

我最大的困难是使输出波纹管

{
    "text": "ubx",
    "children" : [{
        "text": "ubx-producao",
        "children": [{
            "text": "Editora Abril",
            "children": [{
                "text": "Exame 1106",
                "children": [
                    "BRASIL ECONOMIA DUPLA EXPLOSIVAE.mp3","BRASIL ECONOMIA PRONTOS PARA O JANTAR.mp3"]
                ]
            }]
        },
        {
            "text": "Editora Alto Astral",
            "children": [{
                "text": "Previsoes signos Fevereiro 2016",
                "children": ["aquario-fevereiro.mp3", "aquario-fevereiro.mp3.sfk"]
            }]
        }]
    }]
}

2 个答案:

答案 0 :(得分:0)

所以我想我几乎能得到您的要求

首先;线程中的输入与预期的输出不匹配。

例如输入中没有 aquario-fevereiro.mp3.sfk

- 另外,输出的格式不正确,因此我进行了一些调整。

这是我假设的预期输出

            let expectedOutput = [{
            "text": "ubx",
            "children" : [
                {
                    "text": "ubx-producao",
                    "children": [
                        {
                            "text": "Editora Abril",
                            "children": [
                                {
                                    "text": "Exame 1106",
                                    "children": ["FINANCAS_INOCAVAO_STARTUP_BANCOES.mp3"]
                                }
                            ]
                        },
                        {
                            "text": "Editora Alto Astral",
                            "children": [
                                {
                                    "text": "Previsoes signos Fevereiro 2016",
                                    "children": ["aquario-fevereiro.mp3", "aries-fevereiro.mp3"]
                                }
                            ]
                        }
                    ]
                }
            ]
        }];

代码如下:

let paths = [
	"ubx/ubx-producao/Editora Abril/Exame 1106/FINANCAS_INOCAVAO_STARTUP_BANCOES.mp3",
	"ubx/ubx-producao/Editora Alto Astral/Previsoes signos Fevereiro 2016/aquario-fevereiro.mp3",
	"ubx/ubx-producao/Editora Alto Astral/Previsoes signos Fevereiro 2016/aries-fevereiro.mp3"
];
let output = convertPathsToStructure(paths);
console.log(output);

function convertPathToStructure(path) {
    let index = path.indexOf('/');
    return (index > -1) ? {
        text : path.substr(0, index),
        children: convertPathToStructure(path.substr(index + 1)),
    } : path;
}
function convertPathsToStructure(paths) {
    return convertTreeStructuresToStructure(paths.map(convertPathToStructure));
}
function convertTreeStructuresToStructure(treeStructures) {
    let isObjects = treeStructures.filter(result => result.hasOwnProperty('text')).length > 0;
    if (!isObjects) return treeStructures;

    let allObjs = {};
    treeStructures.forEach(({text = '', children = []}) => {
        let obj = allObjs[text] || {text: '', children: []};
        obj.text = text;
        obj.children.push(children);
        allObjs[text] = obj;
    });

    return Object.keys(allObjs).map(text => {
        return {
            text: text,
            children: convertTreeStructuresToStructure(allObjs[text].children)
        }
    });
}

答案 1 :(得分:0)

我希望编写紧凑的代码。首先,像您一样构造一棵树,然后遍历该树以格式化该节点

const paths = [
  "ubx/ubx-producao/Editora Abril/Exame 1106/FINANCAS_INOCAVAO_STARTUP_BANCOES.mp3",
  "ubx/ubx-producao/Editora Alto Astral/Previsoes signos Fevereiro 2016/aquario-fevereiro.mp3",
  "ubx/ubx-producao/Editora Alto Astral/Previsoes signos Fevereiro 2016/aries-fevereiro.mp3"
];

// first construct a tree like what you have
const tree = paths.reduce((res, cur) => {
  const arr = cur.split("/");
  const strParent = arr.shift();
  res[strParent] = res[strParent] || {}; 
  let parent = res[strParent];

  arr.forEach(item => {
    parent[item] = parent[item] || {};
    parent = parent[item];
  });
  return res;
}, {});

// traverse the tree to format the results
const wrap = (parent) => {
  return Object.getOwnPropertyNames(parent).map(name => {
    const node = {
      text: name,
      children: wrap(parent[name])
    };

    node.children = node.children.map(c => {
      return c.children.length === 0 ? c.text : c;
    });

    return node;
  }); 
}

console.log(JSON.stringify(wrap(tree), null, 2));