Different result from JSON.parse using Firefox Scratchpad vs node/JSFiddle

最后都变了- 提交于 2021-02-10 18:49:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!