YD8877
YD8877

Reputation: 10790

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

Upvotes: 2

Views: 18784

Answers (5)

Kai G
Kai G

Reputation: 3502

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" 
      } 
    ]
  }
]

Upvotes: 0

Gobhi
Gobhi

Reputation: 74

Try something like this:

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

Upvotes: -1

DrStrangeLove
DrStrangeLove

Reputation: 11557

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

Upvotes: 9

surj
surj

Reputation: 4903

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.

Upvotes: 5

Eric
Eric

Reputation: 97601

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

Upvotes: 2

Related Questions