How to find if a valid JSON string

55 views Asked by At

Hello guys Is there a way to know if a string is a valid JSON type string in lazarus. I have been using GetJSON(testString) but throws an error if string is not JSON type. Thanks

1

There are 1 answers

0
Kai Burghardt On

FPJSON.getJSON raises an exception if data does not contain a valid JSO in JSON. Probably you do not want to just detect valid JSON (you do use the getJSON function), but want to continue further processing with correctly parsed data if there is any. Therefore you can simply presume data is valid and rely on the exception should there be invalid data:

program invalidJavaScriptObjectNotationDemo(input, output, stdErr);
    {$modeSwitch exceptions+}
    uses
        sysUtils, FPJSON, JSONParser;
    var
        JSO: tJSONData;
    begin
        try
            try
                JSO := getJSON('foo');
                { … continue doing other stuff with JSO … }
            finally
                JSO.free
            end
        except
            on status: exception do
                writeln(stdErr, 'An Exception occurred when parsing: ',
                                 status.message);
        end
    end.