Search code examples
javascriptjsonbit.ly

Parsing Bit.ly JSON response in Javascript (url in json response)


I'm trying to extract the shortUrl from the Bit.ly JSON response. The problem is the original URL is included in the response, using the dot notation to traverse the response doesn't work? I can get the other attributes (errorCode, errorMessage etc), but I can't get anything under results beacuse of the URL. Am I missing something?

This is the response:

{
    "errorCode": 0, 
    "errorMessage": "", 
    "results": {
        "http://www.google.com/": {
            "hash": "2V6CFi", 
            "shortKeywordUrl": "", 
            "shortUrl": "http://bit.ly/1F5ewS", 
            "userHash": "1F5ewS"
        }
    }, 
    "statusCode": "OK"
}

Solution

  • Javascript objects can be accessed via dot notation (obj.property) if and only if the property name is also a valid Javascript identifier.

    In your example, since a URL is clearly not a valid identifier, you can use the other method, array-style access (obj[property]):

    var obj = {
       yahoo: 5
       'http://www.google.com':10
    };
    
    // Both of these work just fine.
    var yahoo = obj.yahoo;
    var google = obj['http://www.google.com'];