2013-11-02 76 views
6

我正在试验JSON格式,并不确定如何使用它来构建族树。这是我得到的(保持简单,只列出父亲,他的孩子以及这些孩子是否有孩子,我没有列出配偶的姓名)。虽然它的效果很好,但我不知道这样做的最佳方法(即我的方法干干净净,例如可伸缩)。如何创建JSON格式的家族树结构

+3

您识别人通过他们的名字。名称不是唯一的,因此这是一个糟糕的结构。 ID更适合于需要唯一性的情况。 – ComFreek

+0

这个数据是_users_ type还是创建的东西? – Bulkan

+1

@Bulkan号这是我正在创建的数据。 – Andy

回答

4

最简单的办法:

{ 
    "Jonathan Smith": { 
     "Adam": { 
      "Suzy": {}, 
      "Clare": {}, 
      "Aaron": {}, 
      "Simon": {} 
     }, 
     "Timmy": {}, 
     "Alison": { 
      "Natasha": {}, "Zak": {} 
     } 
    } 
} 

更强大的结构:

{ 
    "Smiths": { 
     "Jonathan Smith": { "id": 0}, 
     "Adam Smith": { "id": 1, "father": 0 }, 
     "Suzy Smith": { "id": 4, "father": 1 }, 
     "Clare Smith": { "id": 5, "father": 1 }, 
     "Aaron Smith": { "id": 6, "father": 1 }, 
     "Simon Smith": { "id": 7, "father": 1 }, 
     "Timmy Smith": { "id": 2, "father": 0 }, 
     "Alison Smith": { "id":3, "father": 0 }, 
     "Natasha Smith": { "id": 8, "father": 3 }, 
     "Zak Smith": { "id": 9, "father": 3 } 
    } 
} 

添加更多的关系,母亲,丈夫和妻子。

{ 
    "Smiths": { 
     "Jonathan Smith": { "id": 0, "wife": [10]}, 
     "Suzan Smith": { "id": 10, "born": "Suzan Jones", "husband": [0] }, 
     "Adam Smith": { "id": 1, "father": 0, "mother": 10 }, 
     "Suzy Smith": { "id": 4, "father": 1 }, 
     "Clare Smith": { "id": 5, "father": 1 }, 
     "Aaron Smith": { "id": 6, "father": 1 }, 
     "Simon Smith": { "id": 7, "father": 1 }, 
     "Timmy Smith": { "id": 2, "father": 0, "mother": 10 }, 
     "Alison Smith": { "id":3, "father": 0, "mother": 10 }, 
     "Natasha Smith": { "id": 8, "father": 3 }, 
     "Zak Smith": { "id": 9, "father": 3 } 
    } 
} 

有时它是非常容易使用Javascript

var familyTree = {} 
familyTree["Dick Jones"] = { id: 1234, father: 213 } 

使用JSON工作这将允许您添加,删除,使用的功能,能够检查错误,然后就拿到产生JSON致电:

JSON.stringify(familyTree) 
0

你必须注意,因为你添加的覆盖格式json数据。尝试使用允许您以简单的方式响应您想要执行的查询的结构。

0

试试这个:

{'name': 'John'}, {'name': 'Jack', 'child_of': 'John'}, {'name': 'Charlie', 'child_of': 'Jack', 'grand_child_of': 'John'} 
0

树木的工作是很困难的JSON,但也许你可以使用等级的概念(代在这个例子中),这样你可以了解叔伯,堂兄弟等

[ 
    { 
     "id":100, 
     "name":"Jhon Smith", 
     "generation":1, 
     "children":[ 
     { 
      "id":101, 
      "name":"Michael Smith", 
      "generation":2, 
      "children":null 
     }, 
     { 
      "id":102, 
      "name":"Diana Smith", 
      "children":[ 
       { 
        "id":301, 
        "name":"Britney Smith", 
        "generation":3, 
        "children":null 
       } 
      ] 
     } 
     ] 
    }, 
    { 
     "id":200, 
     "name":"Richard Smith", 
     "generation":1, 
     "children":[ 
     { 
      "id":101, 
      "name":"Michael Smith", 
      "generation":2, 
      "children":null 
     }, 
     { 
      "id":102, 
      "name":"Diana Smith", 
      "generation":2, 
      "children":null 
     } 
     ] 
    } 
]