views:

636

answers:

7

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

A: 
var responseAsJSON = eval(jsonString);
alert(responseAsJSON.shortUrl);
Ken Browning
+1  A: 

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.

adrian
A: 

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

jimyshock
A: 

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.

bjoernwibben
+1  A: 

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'];
Triptych
A: 

Thanks for this nice post.

Goysar
A: 

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

James Grady