views:

815

answers:

2

I'm trying to parse bit.ly JSON reply in javscript.

I get the JSON vis XmlHttpRequest.

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url) + BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};
req.send(null);

parseJSON: function(req, url) {
if (req.status == 200) {
var jsonResponse = req.responseJSON;
var bitlyUrl = jsonResponse.results[url].shortUrl;
}

I do this in a firefox addon. When I run I get the error "jsonResponse is undefined" for line var bitlyUrl = jsonResponse.results[url].shortUrl;. Am I doing anything wrong in parsing JSON here? Or what is wrong with this code?

+1  A: 

I think you have to include jQuery to use responseJSON.

Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");

UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.

OR

use json_parse : it does not use eval

S.Mark
For a Firefox addon running with chrome privs, don't try to eval anything you get from an outside source. Instead, use JSON.parse (at least in FF 3.5 and later).
Ben Combee
A: 

Or use jquery.parseJSON

florin