var primariesText, primaries;
//var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; //node
var requestURL = 'https://raw.githubusercontent.com/WFCD/warframe-items/development/data/json/Primary.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
primariesText = request.response;
//console.log(primariesText);
}
primaries = JSON.parse(JSON.stringify(primariesText[0]));
console.log(primaries);
我在3个解析器中尝试了此脚本,并得到了不同的结果:
当我在Firefox的暂存器中运行它时,它会很好地输出JS对象。
当我在node或JSFiddle https://jsfiddle.net/bn56hspk/中运行它时,我得到了
TypeError: Cannot read property '0' of undefined
指向primariesText [0]数组。
我把[0]放在这里的原因是为了摆脱大多数括号。我尝试了两个primariesText []
SyntaxError: Unexpected token ]
或primariesText
节点:
SyntaxError: Unexpected token u in JSON at position 0
JSFiddle:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
都不行。
我想念什么?
答案 0 :(得分:1)
这里的问题是您尝试在调用onload
函数之前在 之前解析JSON。因此primariesText
只是不确定的。
这里,我在onload
函数中对其进行了解析,并按预期工作(请注意,闭合的大括号}
在代码末尾处结束)
var primariesText, primaries;
//var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; //node
var requestURL = 'https://raw.githubusercontent.com/WFCD/warframe-items/development/data/json/Primary.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
primariesText = request.response;
//console.log(primariesText);
primaries = JSON.parse(JSON.stringify(primariesText[0]));
console.log(primaries)
}