如何查找有效的 JSON 字符串

问题描述 投票:0回答:1

大家好,有没有办法知道拉撒路中的字符串是否是有效的 JSON 类型字符串。 我一直在使用 GetJSON(testString) 但如果字符串不是 JSON 类型,则会抛出错误。 谢谢

pascal lazarus
1个回答
0
投票
如果数据在 JSON 中不包含有效的 JSO,则

FPJSON.getJSON
会引发异常。 您可能不想just检测有效的JSON(您确实使用
getJSON
函数),但希望使用正确解析的数据(如果有)继续进一步处理。 因此,您可以简单地依赖异常:

program NotJavaScriptObjectNotationDemo(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.
© www.soinside.com 2019 - 2024. All rights reserved.