nomethod 发表于 2016-05-11 16:02

格式化数据

看网上的一个题, 不知道如何做比较好。

原格式:
[{
    "id": 1,
    "title": "node1",
    "parent": "null"
},
{
    "id": 2,
    "title": "node2",
    "parent": 1
},
{
    "id": 3,
    "title": "node3",
    "parent": 1
},
{
    "id": 4,
    "title": "node4",
    "parent": 2
},
{
    "id": 5,
    "title": "node5",
    "parent": 2
}]

目标格式:
    [{
      'id':1,
      'title':'node1',
      'childs':[
         {
            'id':2,
            'title':'node2'
            'childs':[
               {
                  'id':4,
                  'title':'node4',
                  'childs': []
               },
               {
                  'id':5,
                  'title':'node5',
                  'childs': []
               }
            ]
         },
         {
            'id':3,
            'title':'node3'
            'childs':[]
         }
      ]
   }]

q1208c 发表于 2016-05-11 21:56

简单的 字典替换。


现在的学生都这么懒么?:em06:

nomethod 发表于 2016-05-11 22:07

回复 2# q1208c


    有什么好办法?

不做学生很多年了。

nomethod 发表于 2016-05-11 22:15

回复 2# q1208c


    求大神赐教

timdcn 发表于 2016-05-12 16:00

不就把“换成‘吗,有啥难的?

nomethod 发表于 2016-05-12 17:13

回复 5# timdcn


    可能是难者亦易矣 的问题。

我真想了一天没想个好办法出来

mswsg 发表于 2016-05-12 18:13

google会有答案,有时比这里快,就看你会不会搜了

nomethod 发表于 2016-05-12 19:44

回复 7# mswsg


    大神来一发?

   

nomethod 发表于 2016-05-12 20:39

stackoverflow 题目链接

stackoverflow.com/questions/37130131/converting-list-of-dictionary-to-dictionary-tree-based-on-parent-id/37155801

有两个答案了, 感觉不完美。

Linux_manne 发表于 2016-05-12 23:50

回复 9# nomethod


    第一个写法 简洁 也符合深层次嵌套 不是挺好的么 ..... 本人的太ugly 了 :cry: ... 就不贴了...
页: [1]
查看完整版本: 格式化数据