www.webdeveloper.com
Results 1 to 4 of 4

Thread: Parsing JSON Boolean Values?

  1. #1
    Join Date
    May 2007
    Posts
    14

    Parsing JSON Boolean Values?

    Hello,

    Been on this one for hours. When parsing a JSON response string from an ajax call, the 'true/false' values are put into an array as a string (not boolean). The json string does not have boolean values enclosed in quotes. Also, return header is application/x-json.

    I've tried prototype, crockford, byteson and plain straight eval(responseText) but a boolean value returned has a string type. Is there any way to make a boolean value have a boolean type in JS?

    Thanks!

  2. #2
    Join Date
    Feb 2006
    Posts
    2,927
    You can coerce a string to return another type with a string method-

    Code:
    String.prototype.revalue= function(){
        if(/^(true|false|null|undefined|NaN)$/i.test(this)) return eval(this);
        if(parseFloat(this)+''== this) return parseFloat(this);
        return this;
    }
    Last edited by mrhoo; 05-05-2007 at 06:26 PM.

  3. #3
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by racecar789
    Hello,

    Been on this one for hours. When parsing a JSON response string from an ajax call, the 'true/false' values are put into an array as a string (not boolean). The json string does not have boolean values enclosed in quotes. Also, return header is application/x-json.

    I've tried prototype, crockford, byteson and plain straight eval(responseText) but a boolean value returned has a string type. Is there any way to make a boolean value have a boolean type in JS?

    Thanks!
    Are you saying that you have an array of strings in which each element contains either 'true' or 'false', and you want them all converted to booleans? If so, I think this should do it:
    Code:
    for(var i=0; i<responseArray.length; i++)
     responseArray[i]=/^true$/i.test(responseArray[i]);
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  4. #4
    Join Date
    May 2007
    Posts
    14
    Hey that does it, thanks a bunch mrhoo and Logic Ali!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles