我正在使用SuperObject在JSON中创建和操作简单的层次结构。
我的目标是将一组对象{“ id”:...,“ name”:...,“ parent”:...}转换为层次结构。示例:
我想改变这个
{"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"},
进入此
{
"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"
}
]
}
]
}
]
}
(此结构可以变化,即没有固定的模型。这可能意味着解决方案必须是递归的。)
我认为实现这一目标的方法是:
为此,我正在寻找一种检索对象路径的方法,例如
function findpathinObject(key:string, value:string, object:iSuperObject):string
,它将返回找到的值的“路径”。
在我的示例中,findpathinObject(“ parent”,“ 0003.1”,newObject)将返回'items [2] .items [0]'
这是一个好方法吗?有什么可以解决我的问题而又不增加新功能的吗?
我所看到的最接近的是这个 SuperObject - Extract All 但我不知道是否可以更改该值以返回它正在查找的路径,或最终找到该值的路径...
谢谢
答案 0 :(得分:0)
SuperObject是JSON访问库,而不是数据处理库。因此,框中没有像这样的东西。
您只需要用Pascal代码实现提取逻辑,就可以使用SuperObject读取输入并创建嵌套的输出。
答案 1 :(得分:0)
从Python获得了这一点: Sorting JSON object(s) into a Hierarchy
在Delphi中(有效,这是指导的摘录):
function ProcessObject(const aAsObject: iSuperObject): iSuperObject;
var
var KeyedObject: iSuperObject
item: iSuperObject;
ArrayItem: iSuperObject;
parent, tgt: iSuperObject;
begin
KeyedObject := SO('{}');
for ArrayItem in aAsObject do
begin
KeyedObject[ArrayItem['id'].AsString] := ArrayItem;
end;
// iterate through each item in the `myJson` list.
for item in aAsObject do
begin
// does the item have a parent?
if assigned(item['parent.id']) then
begin
// get the parent item
if (assigned(item['parent']) and assigned(item['parent.id'])) then
begin
if (assigned(KeyedObject[item['parent'].AsString])) then
parent := KeyedObject[item['parent.id'].AsString];
// if the parent item doesn't have a "children" member,
// we must create one.
if not(assigned(parent['children'])) then
parent['children'] := SO('{[]}');
// add the item to its parent's "children" list.
parent['children[]'] := item;
end;
end;
end;
tgt := SO('{}');
for item in aAsObject do
if not assigned(item['parent']) then
tgt[] := item;
result := tgt;
end;