Write json text

I am using lkJSON-1.07 in delphi 7, in their example

js := TlkJSONobject.Create; js.Add('namestring','namevalue'); // get the text of object s := TlkJSON.GenerateText(js); writeln(s); writeln; writeln('more readable variant:'); // (ver 1.03+) generate readable text i := 0; s := GenerateReadableText(js,i); writeln(s); js.Free; 

it generates the following text: {"Namestring": "name-value"}

How to write json text format like this:

 { "Users": { "test_user1": { "time":1600, "Points":4 } "test_user2": { "time":1500, "Points":3 } } } 
+5
source share
1 answer

When using the JSON Delphi Library, you must accept the method that follows to add JSON children to the parents:

 function TlkJSONobject.Add(const aname: WideString; aobj: TlkJSONbase): Integer; 

This method allows you to bind the aobj parameter as a child of aname .

The code below allows you to complete your task:

 var js0, js1, js2, js22: TlkJSONobject; s: string; i: Integer; begin js2 := TlkJSONobject.Create; js2.Add('time', '1600'); js2.Add('Points', 4); js22 := TlkJSONobject.Create; js22.Add('time', '1500'); js22.Add('Points', 3); js1 := TlkJSONobject.Create; js1.Add('test_user1', js2); js1.Add('test_user2', js22); js0 := TlkJSONobject.Create; js0.Add('Users', js1); i := 0; s := GenerateReadableText(js0, i); WriteLn(s); js0.Free; end; 

This is a more suitable way to write the previous code - but less readable, in my opinion.

The idea here is to create elements in the natural order of the relationship between parents and children: children are added to the already inserted parent using the Field property of the TlkJSONobject object.

Note that js.Field['some string'] same as js['some string'] because of the default directive applied to the Field property.

 var js: TlkJSONobject; s: string; i: Integer; begin js := TlkJSONobject.Create; try js.Add('Users', TlkJSONobject.Create); with TlkJSONobject(js['Users']) do begin Add('test_user1', TlkJSONobject.Create); Add('test_user2', TlkJSONobject.Create); end; with TlkJSONobject(TlkJSONobject(js['Users'])['test_user1']) do begin Add('time', '1600'); Add('Points', 4); end; with TlkJSONobject(TlkJSONobject(js['Users'])['test_user2']) do begin Add('time', '1500'); Add('Points', 3); end; i := 0; s := GenerateReadableText(js, i); WriteLn(s); finally js.Free; end; end; 

Starting a project, it prints:

 { "Users":{ "test_user1":{ "time":"1600", "Points":4 }, "test_user2":{ "time":"1500", "Points":3 } } } 

In the real case, you will obviously think about creating objects and adding children using some loop statement.

+3
source

Source: https://habr.com/ru/post/1233042/


All Articles