csv到多层次json来创建树

ibrsph3r  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(90)

我从菜单中创建了CSV

Main,Level 1,Level 2 ,Level 3,Level 4 
Forest,,,,
,lvl1link,,,
,,lvl2link,,
,,lvl2link2,,
Cloud,,,,
,clv1,,,
,,clvl2,,
,,clvl22,,
,,,clvl3,
,,,,clvl4
Energy,,,,
,enlvl1,,,
,enlvl11,,,
,,enlvl2,,
,,,enlvl3,
,,,enlvl31,

我从另一个项目导出CSV,我需要创建子网站,并重新创建菜单结构。
如何将其转换为JSON,其中Forestlvl1link的父级,lvl1linklvl2linklvl2link2等的父级。
在我看来,它可以通过一些递归函数来完成。
示例步骤

  • 检查具有Main元素值的前2行的索引,并记录其索引
  • 现在,当查找col2中的元素时,请检查第二行的索引,并注意它们的索引
  • 通过重复以上步骤构建多维数组,并返回以下内容
array(
  'Forest' => array(
    'lvl1link' => array(
      'lvl2link',
      'lvl2link2'
    )
  ),
  'Cloud' => array(
    'clv1' => array(
      'clvl2',
      'clvl22' => array(
        'clvl3' => array(
          'clvl4'
        )
      )
    )
  ),
  'Energy' => array(
    'enlvl1',
    'enlvl11' => array(
      'enlvl2' => array(
        'enlvl3',
        'enlvl31'
      )
    )
  )
);

我可以使用PHP,Python或JavaScript。
请告诉我正确的方向

o4tp2gmn

o4tp2gmn1#

上下文和目标对我来说并不清楚,但是我会将CSV加载到数据库中,然后执行适当的查询以获得连接结果。例如,Talisman MPCS解决方案能够将csv加载到支持In-Memory SQL的数据存储中,并公开服务以自动生成JSON查询结果。

drkbr07n

drkbr07n2#

使用递归遍历整个结构

console.log(composify(`a\n,b`))
/* => [
  {
    el: ['a'],
    children: [
      {el: 'b'},
    ],
  }
]*/

function composify(arr, root = []) {
  if (!arr.push) arr = arr.split("\n").map(line => line.split(','));
  let p = null;
  arr.forEach((row, i) => {
    if (row.every(Boolean) && p) return;
    const cell = row[0]
    if (cell) {
        if (p) {
            p.children = composify(p.children);
        }
        p = {el: row.filter(Boolean), children: []};
        root.push(p)
        return;
    }
    p.children.push(row.slice(1))
  })
  if (p) p.children = composify(p.children)
  return root
}
function composify(arr, root = []) {
  let p = null;
  arr.forEach((row, i) => {
    if (row.every(Boolean)) return;
    const cell = row[0]
    if (cell) {
        if (p) {
            p.children = composify(p.children);
        }
        p = {el: row.filter(Boolean), children: []};
        root.push(p)
        return;
    }
    p.children.push(row.slice(1))
  })
  if (p) p.children = composify(p.children)
  return root
}
function handle() {
  const vec2d = window.csv.value.split("\n").map(line => line.split(','));
  const tree = composify(vec2d)
  const str = JSON.stringify(tree, null, 2)
  console.log('str', str);
  window.json.textContent = str
}
handle()
body, html {
  height: 600px;
}
.flex {
  display: flex;
}
textarea, pre, .flex {
  resize: both;
  overflow: auto;
}
<div class="flex">
<textarea oninput="handle()" spellcheck="false" id="csv"
>Main,Level 1,Level 2 ,Level 3,Level 4 
Forest,,,,
,lvl1link,,,
,,lvl2link,,
,,lvl2link2,,
Cloud,,,,
,clv1,,,
,,clvl2,,
,,clvl22,,
,,,clvl3,
,,,,clvl4
Energy,,,,
,enlvl1,,,
,enlvl11,,,
,,enlvl2,,
,,,enlvl3,
,,,enlvl31,</textarea
>
<pre id="json"></pre>
</div>

相关问题