Question

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"
}
Was it helpful?

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'];

OTHER TIPS

eval will work to parse JSON, but it is often considered unsafe because it allows the JSON file to execute whatever code it likes. This question discusses why and indicates some safer ways to parse JSON.

var responseAsJSON = eval(jsonString);
alert(responseAsJSON.shortUrl);

From your sample JSON object, I would expect "http://www.google.com/" to be the name of a sub-object (like "results"). Let's say you replaced "http://www.google.com/" with "link" instead. You could then reference "shortUrl" like this (response.results.link.shortUrl) and that would return "http://bit.ly/1F5ewS".

Try this one:

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

var theShortURL = myJSONResponse.results["http://www.google.com/"].shortUrl;

theShortURL will hold http://bit.ly/1F5ewS as the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top