[fpc-pascal] Parse JSON

Michael Van Canneyt michael at freepascal.org
Sun Jun 25 23:17:01 CEST 2023



On Fri, 23 Jun 2023, Darius Blaszyk via fpc-pascal wrote:

> Hi all,
>
> I've hardly done anything with JSON in Freepascal before, so apologies for 
> the trivial question. I want to traverse an array in JSON and retrieve the 
> elements (which I don't know what they are in advance) one by one. An example 
> of the JSON file is given below.
>
> "keywords": {
>      "key": "value",
>      "key1": "value1",
>      "key2": "value2"
> },
>
> Ideally, I'd like to be able to stick to the FPC out-of-the-box library. Any 
> help would be appreciated.
>

Something like:

uses classes, fpjson;

var
   J : TJSONObject;
   F : TFileStream;

begin
   J:=nil;
   F:=TFileStream.Create('yourfile.json',fmOpenRead);
   try
     J:=GetJSON(F) as TJSONObject;
     For I:=0 to J.Count-1 do
       Writeln(J.Names[i],' : ',J.AsString);
   finally
     J.Free;
     F.Free;
   end;
end.



More information about the fpc-pascal mailing list