Axios API response JSON body has "true/false" as string type not boolean

Viewed 5072

I am working on converting angularjs application to react and decided to use axios for API request. Everything work fine except some response body with JSON type but the boolean values are string type not boolean. It works fine with angularJs $http but some of endpoints returns like that.

The modules are AngularJs + Typescript 2.9.1 + axios 0.19.0

let request = Axios({
    ...requestConfig,
    url: resource, method: 'get', responseType: 'json'
}).then(response => response);

and the response body is

{
   some: "true"
}

but I am excepting

{
   some: true
}

Any ideas?

1 Answers

[UPDATE] as Phil pointed out, Boolean('false') does not work. I updated the code to something that will work for 'true' and 'false', but a more complex function is needed if you want to cover all possibilities.


If the response by the API exactly looks like this:

{
  "some": "true"
}

Then axios is not doing anything wrong. It's dangerous for a library to automagically parse values as they see fit, just look at how Json.NET handles values that they think look like Datetime.

If the payload returned by the API looks exactly like this:

{
  "some" : true
}

Then axios should parse it as a boolean directly.

What I propose you do, is to always parse the value as a boolean, even if it is already one:

let request = await Axios({...requestConfig,
      url: resource, method: 'get', responseType: 'json'
    });

let someValue = String(request.data.some) == "true";

This will work for Boolean("true") as well as Boolean(true).

Related