up vote 0 down vote favorite

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?

Thanks

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

link|flag

7 Answers

up vote 1 down vote accepted

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'];
link|flag
up vote 1 down vote

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.

link|flag
up vote 0 down vote
var responseAsJSON = eval(jsonString);
alert(responseAsJSON.shortUrl);
link|flag
up vote 0 down vote

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".

link|flag
up vote 0 down vote

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.

link|flag
up vote 0 down vote

Thanks for this nice post.

link|flag
up vote 0 down vote

I cound a complete example on how to use the bit.ly API with jQuery here: http://www.codecapers.com/post/Building-a-Link-Shortener-with-the-bitly-API.aspx

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.