Javascript 从 XmlHttpRequest.responseJSON 解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1973140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON from XmlHttpRequest.responseJSON
提问by chanux
I'm trying to parse a bit.ly JSON response in javascript.
我正在尝试在 javascript 中解析 bit.ly JSON 响应。
I get the JSON via XmlHttpRequest.
我通过 XmlHttpRequest 获取 JSON。
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 the line var bitlyUrl = jsonResponse.results[url].shortUrl;. Am I doing anything wrong in parsing JSON here? Or what is wrong with this code?
我在 Firefox 插件中执行此操作。当我运行时,我收到该行的错误“jsonResponse 未定义” var bitlyUrl = jsonResponse.results[url].shortUrl;。我在这里解析 JSON 时做错了什么吗?或者这段代码有什么问题?
回答by Torben
New ways I: fetch
新方法我: fetch
TL;DRI'd recommend this way as long as you don't have to send synchronous requests or support old browsers.
TL;DR只要您不必发送同步请求或支持旧浏览器,我就会推荐这种方式。
A long as your request is asynchronous you can use the Fetch APIto send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch()to send a request and ResponseBody.json()to parse the response:
只要您的请求是异步的,您就可以使用Fetch API发送 HTTP 请求。fetch API 与promises 一起工作,这是在 JavaScript 中处理异步工作流的好方法。通过这种方法,您fetch()可以发送请求并ResponseBody.json()解析响应:
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 & 13. However, there are polyfills.
兼容性:IE11 以及 Edge 12 和 13 不支持 Fetch API。但是,有polyfills。
New ways II: responseType
新方法二: responseType
As Londerenhas written in his answer, newer browsers allow you to use the responseTypeproperty to define the expected format of the response. The parsed response data can then be accessed via the responseproperty:
正如Londeren在他的回答中所写的那样,较新的浏览器允许您使用该responseType属性来定义响应的预期格式。然后可以通过response属性访问解析的响应数据:
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'is not supported by IE11.
兼容性:responseType = 'json'IE11 不支持。
The classic way
经典的方式
The standard XMLHttpRequest has no responseJSONproperty, just responseTextand responseXML. As long as bitly really responds with some JSON to your request, responseTextshould contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():
标准的 XMLHttpRequest 没有responseJSON属性,只有responseText和responseXML。只要 bitly 真的用一些 JSON 响应您的请求,就responseText应该包含 JSON 代码作为文本,所以您要做的就是使用以下内容解析它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 XMLHttpRequestand JSON.
兼容性:这种方法应该适用于任何支持XMLHttpRequest和 的浏览器JSON。
JSONHttpRequest
JSONHttpRequest
If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSONproperty. All you have to change in your code would be the first line:
如果您更喜欢使用responseJSON,但想要一个比 JQuery 更轻量级的解决方案,您可能需要查看我的 JSONHttpRequest。它的工作方式与普通的 XMLHttpRequest 完全一样,但也提供了responseJSON属性。您只需在代码中更改第一行:
var req = new JSONHttpRequest();
JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.
JSONHttpRequest 还提供了将 JavaScript 对象作为 JSON 轻松发送的功能。更多细节和代码可以在这里找到:http: //pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/。
Full disclosure: I'm 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 remove the link.
完全披露:我是 Pixels|Bytes 的所有者。我认为我的脚本很好地解决了这个问题,所以我把它贴在这里。如果您希望我删除链接,请发表评论。
回答by Londeren
You can simply set xhr.responseType = 'json';
你可以简单地设置 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();
回答by cocco
Note: I've only tested this in Chrome.
注意:我只在 Chrome 中测试过。
it adds a prototype function to the XMLHttpRequest .. XHR2,
它向 XMLHttpRequest .. XHR2添加了一个原型函数,
in XHR1 you probably just need to replace this.responsewith this.responseText
在XHR1 中,您可能只需要替换this.response为this.responseText
Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
return JSON.parse(this.response);
},writable:false,enumerable:false});
to return the json in xhr2
在 xhr2 中返回 json
xhr.onload=function(){
console.log(this.responseJSON());
}
EDIT
编辑
If you plan to use XHR with arraybufferor other response types then you have to check if the response is a string.
如果您打算将 XHR 与arraybuffer或其他响应类型一起使用,那么您必须检查响应是否为string.
in any case you have to add more checks e.g. if it's not able to parse the json.
在任何情况下,您都必须添加更多检查,例如,如果它无法解析 json。
Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
return (typeof this.response==='string'?JSON.parse(this.response):this.response);
},writable:false,enumerable:false});
回答by YOU
I think you have to include jQuery to use responseJSON.
我认为您必须包含 jQuery 才能使用responseJSON.
Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");
如果没有 jQuery,你可以尝试使用 responseText 并尝试像 eval("("+req.responseText+")");
UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.
更新:请阅读关于 的评论eval,您可以使用 eval 进行测试,但不要在工作扩展中使用它。
OR
或者
use json_parse: it does not use eval
使用json_parse:它不使用eval
回答by erikvold
Use nsIJSONif this is for a FF extension:
如果这是用于 FF 扩展,请使用nsIJSON:
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.parseinstead of Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode
对于网页,只需使用JSON.parse代替Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode

