简体   繁体   中英

Represent hierarchy in a JSON object

I need to represent this hierarchy in a JSON object. Can someone help me out ?

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

How about this:

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

The relationship, whether it be children or otherwise, is implied by the tree hierarchy.

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

Similar to the accepted answer but I think it's better to make it an array at the top level, otherwise you can only support one value at the root level. This way the whole data structure is also recursive.

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

尝试这样的事情:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM