I need to represent this hierarchy in a JSON object. Can someone help me out ?
- John
--- Lee
------ Nash
--------- Tim
------ Nicole
------ Kelly
--- Alice
--- Stanley
I need to represent this hierarchy in a JSON object. Can someone help me out ?
- John
--- Lee
------ Nash
--------- Tim
------ Nicole
------ Kelly
--- Alice
--- Stanley
Share
Improve this question
asked Feb 26, 2011 at 21:31
YD8877YD8877
10.8k20 gold badges69 silver badges97 bronze badges
2
- 1 Is this a JSON or a JavaScript question? JSON and JavaScript object literal notation are very similar but other than that, JSON is not related to JavaScript. So if you only talk about JSON, you don't need JavaScript. What is the relation between the names? – Felix Kling Commented Feb 26, 2011 at 21:39
- So, this example can be given a simple example as the accepted one by DrStrangeLove below-- this is because you only encounter each name once and we assume there is very simple logic consuming the data. A more robust solution might include UUID/GUID identifiers for each person, the name, and a list type field specifying a parent entity via the UUID/GUID to provide the ability to create a hierarchy relationships. Things get messy under this strategy for more than 1 parent. – BradChesney79 Commented Sep 10, 2017 at 21:02
5 Answers
Reset to default 9{
"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"
}
]
}
]
Try something like this:
{"name": "John", "children": [ {"name": "Lee", "children": {...}}, {name:"Alice", "children": {..}} ] }