I'm using SuperObject to create and manipulate a simple hierarchical structure in JSON.
My goal is to transform a set of objects {"id":..., "name":..., "parent":...} into a hierarchical structure. Example:
I want to transform this
{"id": "0001","name": "item0001", "parent":""},
{"id": "0002","name": "item0002", "parent":""},
{"id": "0003","name": "item0003", "parent":""},
{"id": "0003.1","name": "item0003.1", "parent":"0003"},
{"id": "0003.1.1","name": "item0003.1.1", "parent":"0003.1"},
into this
{
"items": [
{
"id": "0001",
"name": "item0001"
},
{
"id": "0002",
"name": "item0002"
},
{
"id": "0003",
"name": "item0003",
"items": [
{
"id": "0003.1",
"name": "item0003.1",
"items": [
{
"id": "0003.1.1",
"name": "item0003.1.1"
}
]
}
]
}
]
}
(This structure can vary, i.e. there is no fixed model. Which probably means the solution must be recursive).
I think the way to achieve this is:
- for each object to add,
- if there is no parent, add it to the output json, at the top;
- if there is a parent, find where the parent is in the output json.
- add the object to the output json under the parent.
To do this, I was looking for a way to retrieve the path of an object, like
function findpathinObject(key:string, value:string, object:iSuperObject):string
which would return the "path" of the value found.
In my example, findpathinObject("parent", "0003.1", newObject) would return 'items[2].items[0]'
Is this a good approach? Is there something that resolves my issue without making a new function?
the closest I've seen is this SuperObject - Extract All but I don't know if that can be changed to return the path it is looking in, or the path where it finally found the value...
Thanks
Got this from Python: Sorting JSON object(s) into a Hierarchy
In Delphi (it works, here is an extract for guidance):