Hey Marion,
I am studying the fpjson unit but I can't see how to read and write the json to disk?
I have these 2 function that I use to get my
TJSONData objects:
function GetJSONData(const aJSON: UTF8String): TJSONData;
var
jParser: TJSONParser;
begin
Result := nil;
{$IF FPC_FULLVERSION >= 30002}
jParser := TJSONParser.Create(aJSON, [joUTF8, joIgnoreTrailingComma]);
{$ELSE}
jParser := TJSONParser.Create(aJSON, True);
{$ENDIF}
try
Result := jParser.Parse;
finally
jParser.Free;
end;
end;
function GetJSONData(const aStream: TStream): TJSONData;
var
jParser: TJSONParser;
begin
Result:= nil;
aStream.Position:= 0;
{$IF FPC_FULLVERSION >= 30002}
jParser:= TJSONParser.Create(aStream, [joUTF8, joIgnoreTrailingComma]);
{$ELSE}
jParser := TJSONParser.Create(aStream, True);
{$ENDIF}
try
Result:= jParser.Parse;
finally
jParser.Free;
end;
end;
This makes it easy to then do this:
var
stringStream: TStringStream;
jsonRoot: TJSONData;
begin
// Using GetJSONData with a String
stringStream:= TStringStream.Create('', TEncoding.UTF8);
stringStream.LoadFromFile('/path/to/the/JSON/file');
jsonRoot:= GetJSONData(stringStream.UnicodeDataString);
stringStream.Free
end;
or this:
var
fileStream: TFileStream;
jsonRoot: TJSONData;
begin
// Using GetJSONData with a Stream
fileStream:= TFileStream.Create('/path/to/the/JSON/file', fmOpenRead);
jsonRoot:= GetJSONData(fileStream);
fileStream.Free
end;
If you then want to save:
var
stringStream: TStringStream;
jsonRoot: TJSONData;
begin
stringStream:= TStringStream.Create(jsonRoot.AsJson, TEncoding.UTF8);
stringStream.SaveToFile('/path/to/the/JSON/file');
stringStream.Free
end;
Hope this helps get you started.
Cheers,
Gus