program array2json;
{$MODE OBJFPC}{$H+}
uses
sysutils, jsontools;
type
TMyArray= array [0..9] of integer;
function example1(AArray: TMyArray): TJSonNode;
var
n: integer;
begin
// Create a node
Result:= TJSONNode.Create;
// Make this node an array
Result.kind:= nkArray;
// Fill, this now, array node. Note that for adding values to an array their name is discarded (hence empty)
for n in AArray
do Result.Add('', n);
end;
function example2(ANode: TJSonNode; AName: String; AArray: TMyArray): TJSonNode;
var
JSonArray: TJSonNode;
n: integer;
begin
// Adding an array node with provided name
JSonArray:= ANode.Add(AName, nkArray);
// Fill the array node. Note that for adding values to an array their name is discarded (hence empty)
for n in AArray
do JSonArray.Add('', n);
// Return node to caller
result:= ANode;
end;
function example3(AArray: TMyArray): TJSonNode;
var
n: integer;
i: integer;
s: string;
begin
// Create a node
Result:= TJSONNode.Create;
// Make this node an array
Result.kind:= nkArray;
// convert the array to a string
s:= '[';
for i:= low(AArray) to High(AArray) do
begin
s:= s+AArray[i].ToString;
if i<High(AArray) then s:= s+',';
end;
s:= s+']';
// set the value of the array
Result.Value:= s;
end;
var
MyArray: TMyArray= (10,9,8,7,6,5,4,3,2,1);
JSon: TJSonNode;
begin
// example 1: returns JSONNode as array
WriteLn('--- example 1 ---');
JSon:= example1(MyArray);
WriteLn(JSon.ToString);
JSon.Free;
// example 2: add (named) array to (existing) node
WriteLn('--- example 2 ---');
JSon:= TJSonNode.Create;
JSon:= example2(JSon, 'My_Array', MyArray);
WriteLn(JSon.ToString);
JSon.Free;
// example 3: return JSonNode as array using text conversion
JSon:= example3(MyArray);
WriteLn(JSon.ToString);
JSon.Free;
end.