How to convert JSValue to Boolean?

173 Views Asked by At

I'm doing an API call using TWebHttpRequest and then parsing the response string to a TJSObject, but when I try to get a value from the TJSObject, it comes back as a JSValue. I need to take this JSValue and store it in a Delphi Boolean variable.

Here's my code:

LoginAPI.Execute(
  procedure(AResponse: string; AReq: TJSXMLHttpRequest)
  var
    JS: TJSObject;
    loginSuccess: Boolean;
  begin
    JS := TJSJSON.parseObject(AResponse);

    loginSuccess := JS.Properties['loginSuccess'];

    console.log(loginSuccess);
  end
);

I'm getting the following error:

[Error] Incompatible types: got "JSValue" expected "Boolean"

This error happens on loginSuccess := JS.Properties['loginSuccess'] when I try to get the value and put it into the Boolean variable.

When I do console.log(JS.Properties['loginSuccess']) then I can see that the value is definitely a Boolean in the browser console. So I just need to know how to get it as a Boolean in Delphi.


I tried doing a .AsBoolean, but that doesn't work:

loginSuccess := JS.Properties['loginSuccess'].AsBoolean;

And the error I get then is:

[Error] illegal qualifier "." after "Properties:JSValue"


So, how can I convert this JSValue to a Boolean?

2

There are 2 best solutions below

0
Shaun Roselt On

If you know the property's value is definitely Boolean, then you can just cast it directly to Boolean like this:

loginSuccess := Boolean(JS.Properties['loginSuccess']);
2
AmigoJack On

As per pas2js's documentation its booleaness can be enforced by comparing it to a Boolean literal:

var
  jso: TJSObject;
  jsv: JSValue;
  b: Boolean;
begin
  ...
  jsv:= jso.Properties['any'];
  b:= !(jsv== false);  // Value equals Boolean FALSE? Invert whole meaning.

Casting should only be done if you know what you're doing - but thanks to JavaScript's nature there's no guarantee that anything will always evaluate to either true or false without any further state (like null or undefined).

I have yet not found its actual definition, only DefinedClassesWebKit.pas line #168 with:

JSValue = objcclass external;

...which means the actual definition is elsewhere. Because of the {$modeswitch}s I suspect binaries instead of source code.