Find a TJSONObject in a big nested JSON representing a Tree.

Find a TJSONObject in a big nested JSON representing a Tree.

Hi Gurus,

I get entries from a database table and i should create a nested JSON String representing a tree. The database table can have tousends of entries. Each entry represents a node in the tree. The data i get is sorted by tree level, so i start going trough the entrys and create the root TJSONObjects. Then for the next level i have to find the parent TJSONObject by a value and add the current entry to the parents TJSONArray value and so on....
(I hope somebody understand what i trying to do :-))

My (recursive) implementation for finding a node seems to be very slow:

function FindNode( const Root: TJSONObject; const Caption: String ): TJSONObject;
var
Nodes: TJSONArray;
Value: TJSONValue;
begin
Result := nil;
Nodes := TJSONArray( Root.Values['nodes'] );
for Value in Nodes do begin
if TJSONObject( Value ).GetValue('caption').Value = Caption then begin
Result := TJSONObject( Value );
break;
end else begin
Result := FindNode( TJSONObject( Value ), Caption );
if assigned(Result) then
break;
end;
end;
end;

Maybe there exits some magic library to find a JSON object by value very quickly?

example:
Root.FindTJSONObjectByValue( SearchValue: string ): TJSONObject

Or maybe i am completely on the wrong path?

Any help would be great.

Comments

  1. I think that your mistake is to use JSON to manipulate data instead of using data to produce JSON.

    create a tree of objects with all required informations and then ouput it to JSON (or CSV or XML or whatever you need)

    ReplyDelete
  2. Paul TOTH I saw that in MS SQL Server 2016 you can use the "FOR JSON" to produce JSON direct from Data. I will try this approach.

    ReplyDelete

Post a Comment