JSON parsing from XmlHttpRequest.responseJSON

I am trying to parse the .ly bit of a JSON response in javscript.

I get JSON through 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 start, I get the error "jsonResponse undefined" for the string var bitlyUrl = jsonResponse.results[url].shortUrl; . Am I doing something wrong in JSON parsing here? Or what's wrong with this code?

+55
json javascript firefox-addon
Dec 29 '09 at 5:59
source share
5 answers

New ways I: fetch

TL; DR I would recommend this method until you need to send synchronous requests or support older browsers.

As long as your request is asynchronous, you can use the Fetch API to send HTTP requests. The fetch API works with promises , which is a good way to handle asynchronous workflows in JavaScript. With this approach, you use fetch() to send the request and ResponseBody.json() to parse the response:

 fetch(url) .then(function(response) { return response.json(); }) .then(function(jsonResponse) { // do something with jsonResponse }); 

Compatibility: The Fetch API is not supported by IE11, as well as Edge 12 and 13. However, there are polyfills .

New Ways II: responseType

As Londeren wrote in his answer , new browsers allow the use of responseType to determine the expected response format. Then, the analyzed response data can be obtained through the response property:

 var req = new XMLHttpRequest(); req.responseType = 'json'; req.open('GET', url, true); req.onload = function() { var jsonResponse = req.response; // do something with jsonResponse }; req.send(null); 

Compatibility: responseType = 'json' not supported by IE11.

Classic way

The standard XMLHttpRequest does not have the responseJSON property, only responseText and responseXML . As long as bit-by-bit really answers some JSON to your request, responseText should contain the JSON code as text, so all you have to do is JSON.parse() it with JSON.parse() :

 var req = new XMLHttpRequest(); req.overrideMimeType("application/json"); req.open('GET', url, true); req.onload = function() { var jsonResponse = JSON.parse(req.responseText); // do something with jsonResponse }; req.send(null); 

Compatibility. This approach should work with any browser that supports XMLHttpRequest and JSON .

JSONHttpRequest

If you prefer to use responseJSON but want a lighter solution than jQuery, you can check out my JSONHttpRequest. It works just like regular XMLHttpRequest, but also provides a responseJSON property. All you need to change in your code will be the first line:

 var req = new JSONHttpRequest(); 

JSONHttpRequest also provides functionality for easily sending JavaScript objects as JSON. More information and code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/ .

Full disclosure: I am the owner of Pixels | Bytes. I think my script is a good solution to the problem, so I posted it here. Please leave a comment if you want me to delete the link.

+148
Dec 07 '11 at 2:30 p.m.
source

You can simply set xhr.responseType = 'json';

 const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1'); xhr.responseType = 'json'; xhr.onload = function(e) { if (this.status == 200) { console.log('response', this.response); // JSON response } }; xhr.send(); 

Documentation for responseType

+3
Aug 04 '17 at 8:28
source

I think you should enable jQuery to use responseJSON .

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

UPDATE . Please read the comment regarding eval , you can test with eval, but do not use it in a working extension.

OR

use json_parse : it does not use eval

+2
Dec 29 '09 at 6:19 06:19
source

Note. I tested this only in Chrome.

it adds a prototype function to XMLHttpRequest. XHR2 ,

in XHR 1 you probably just need to replace this.response with this.responseText

 Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){ return JSON.parse(this.response); },writable:false,enumerable:false}); 

to return json in xhr2

 xhr.onload=function(){ console.log(this.responseJSON()); } 

EDIT

If you plan to use XHR with arraybuffer or other types of answers, you need to check if the answer is string .

in any case, you need to add additional checks, for example. if he cannot parse json.

 Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){ return (typeof this.response==='string'?JSON.parse(this.response):this.response); },writable:false,enumerable:false}); 
+2
Jul 12 '13 at 7:27
source

Use nsIJSON if this is for FF extension:

 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 = Components.classes["@mozilla.org/dom/json;1"] .createInstance(Components.interfaces.nsIJSON.decode(req.responseText); var bitlyUrl = jsonResponse.results[url].shortUrl; } 

For a webpage, just use JSON.parse instead of Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode

0
Mar 21 '11 at 6:29
source



All Articles