问题
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);
I tried this script from 3 parser and got different results:
When I run it in scratchpad of Firefox, it outputs the JS object fine.
When I run it in node or JSFiddle https://jsfiddle.net/bn56hspk/, I got
TypeError: Cannot read property '0' of undefined
pointing to the primariesText[0] array.
The reason I put [0] there is to get rid of the out most brackets. I tried both primariesText[]
SyntaxError: Unexpected token ]
or primariesText
node:
SyntaxError: Unexpected token u in JSON at position 0
JSFiddle:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
neither works.
What am I missing?
回答1:
The problem here is that you try to parse the JSON before the onload
function has been called. So primariesText
is just undefined.
Here I parse it inside the onload
function and works as expected (notice how here the closed curly bracket }
ends at the end of the code)
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)
}
来源:https://stackoverflow.com/questions/53179532/different-result-from-json-parse-using-firefox-scratchpad-vs-node-jsfiddle