表示JSON对象中的层次结构

时间:2011-02-26 21:31:54

标签: javascript json

我需要在JSON对象中表示此层次结构。有人可以帮助我吗?

- John
--- Lee
------ Nash
--------- Tim
------ Nicole
------ Kelly
--- Alice
--- Stanley

5 个答案:

答案 0 :(得分:6)

{
  "name": "John", 
  "children": [ 
    {
      "name": "Lee", 
      "children": [
         {
           "name": "Nash", 
           "children": [{ "name":"Tim"}]
         },
         {
           "name": "Nicole"
         },
         {
           "name": "Kelly"
         }
      ]
    },
    {
      "name": "Alice"
    },
    {
      "name": "Stanley" 
    } 
  ] 
}

答案 1 :(得分:5)

这个怎么样:

{
    "John" : {
        "Lee" : {
            "Nash" : {
                "Tim" : null 
            },
            "Nicole" : null,
            "Kelly" : null 
        },
        "Alice" : null,
        "Stanley" : null 
    }
}

树形层次结构暗示了这种关系,无论是儿童还是其他关系。

答案 2 :(得分:1)

["John", [
    ["Lee", [
        ["Nash", [
            ["Tim"]
        ]],
        ["Nicole"],
        ["Kelly"]
    ]],
    ["Alice"],
    ["Stanley"]
]]

答案 3 :(得分:0)

类似于已接受的答案,但我认为最好在顶层将其设置为数组,否则只能在根级别支持一个值。这样,整个数据结构也是递归的。

[
  {
    "name": "John", 
    "children": [ 
      {
        "name": "Lee", 
        "children": [
          {
            "name": "Nash", 
            "children": [{ "name":"Tim"}]
          },
          {
            "name": "Nicole"
          },
          {
            "name": "Kelly"
          }
        ]
      },
      {
        "name": "Alice"
      },
      {
        "name": "Stanley" 
      } 
    ]
  }
]

答案 4 :(得分:-1)

尝试这样的事情:

{"name": "John", "children": [ {"name": "Lee", "children": {...}}, {name:"Alice", "children": {..}} ] }