SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Object or null check

    Hi.
    I've got a json response
    can return or nul or an object.
    I think about
    Code JavaScript:
    alert(null instanceof Object);//false
    alert({id:10} instanceof Object);//true

    Is it the best way ?
    In your opinion null is the best value
    or could be better like 0 or '' (json)?

    Thanks in advance.
    Bye.

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Strange way of checking for this. Also:

    Code javascript:
    alert(typeof null); //object
    alert(typeof {id:1}); //object

    Surely your JSON response is just going to be a string (that's what JSON is, until you parse it). Still, if it's been parsed already, why not just this:

    Code javascript:
    if (response === null) {
      // 
    }
    else if (typeof response === 'Object') {
      //
    }

    But I think just checking for 0 is better. Or even just if (!response). It's hard to say without knowing whether this is after or before parsing JSON and what else is going on.

    Make sure you're using a good JSON parser and not eval, unless you're very sure about what you're doing. (see here)

  3. #3
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Raffles,
    thanks for the advice.
    I'm a spoilt guy I'm using jquery
    so I made
    Code JavaScript:
    if(data.user instanceof Object){
         // do somethink  
    }
    in data.user can handle this values

    Code JavaScript:
    {"user":null}
    or
    {"user":{"id":31}}

    usually I make
    Code JavaScript:
    {"user":null}
    or
    {"user":31}
    and than
    Code JavaScript:
    if( (typeof data.status === 'number')){
          //good value 31
        }
        else {
         //bad value null 
        //typeof null === Object
        }

    but in this case may be
    I need more data (an object with name surname etc)


Bookmarks

Posting Permissions

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