How to use Boolean in Json

Asked

Viewed 1,501 times

0

I have the following JSON, and within my code I have a check to see if autoLogin is enabled.

Object {autoLogin: "true", 
     autoLoginKey: "bWF4LnJvZ2VyaW8=&YWU4NjIwMGJhMTU0NWQzMjQ0ZmRlM2FhYWNiYTJjZmM="}

However to make this use check the value of autoLogin, but I have to check it as string.

if(key.autoLogin === 'true'){//...code}

How do I stop instead of comparing as string, compare as Boolean same.

Type:

if(key.autoLogin === true){//code...}
  • You can try to convert the value to boolean but it is excessive and loses performance for what it is trying to do. For in json come just like boolean has to be placed without the " on the server side and the parse automatically puts the right kind: Object {autoLogin: true

  • Yes, but Seto this value in localStorage: localStorage.setItem('autoLogin', true);, what is the best way to do?

  • In localStorage the value is saved as string so it’s best to compare how string even

  • um.... did not know this detail... If you want to answer I mark as valid.

1 answer

0


Starting from what you indicated in the comment, and if you’re using localStorage to store the value of autoLogin with true in localStorage, this is saved as string. To be more accurate as a DOMString, which is a string in UTF-16 and that is mapped directly to string.

Something that we can see in documentation of the sector

This means it will be guarded as a string and subsequently also obtained as a string through the getItem (documentation).

You could of course try to convert the value that comes from getItem for boolean to make the comparison, using for example the JSON.parse:

if (JSON.parse(key.autoLogin) === true){

Or even make a custom function to convert to boolean, although that’s worse than making the condition you’re already making, like string:

if (key.autoLogin === 'true'){//...code}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.