我想從使用FileReader的文件中讀取JSON對象。 此JSON文件包含以下:由JSON.parse引發的意外令牌e
{"markers": [
{
"point":new GLatLng(40.266044,-74.718479),
"homeTeam":"Lawrence Library",
"awayTeam":"LUGip",
"markerImage":"images/red.png",
"information": "Linux users group meets second Wednesday of each month.",
"fixture":"Wednesday 7pm",
"capacity":"",
"previousScore":""
},
{
"point":new GLatLng(40.211600,-74.695702),
"homeTeam":"Hamilton Library",
"awayTeam":"LUGip HW SIG",
"markerImage":"images/white.png",
"information": "Linux users can meet the first Tuesday of the month to work out harward and configuration issues.",
"fixture":"Tuesday 7pm",
"capacity":"",
"tv":""
},
{
"point":new GLatLng(40.294535,-74.682012),
"homeTeam":"Applebees",
"awayTeam":"After LUPip Mtg Spot",
"markerImage":"images/newcastle.png",
"information": "Some of us go there after the main LUGip meeting, drink brews, and talk.",
"fixture":"Wednesday whenever",
"capacity":"2 to 4 pints",
"tv":""
},
] }
這是我所編寫的代碼:
var jsonClean = function(jsonText) {
return jsonText.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "");
};
if (window.File && window.FileReader && window.FileList && window.Blob) {
console.log('Uploading...');
var uploader = ($('input#fileUpload'))[0];
var fileList = uploader.files;
console.log(fileList.length);
if(fileList.length > 0){
var reader = new FileReader();
reader.addEventListener('load',function(loadEvent){
if(reader.readyState == FileReader.DONE){
var jsonObject = jsonClean(reader.result);
console.log(jsonObject);
$('#jsonView').empty();
$('#jsonView').JSONView(JSON.parse(jsonObject));
}
});
reader.readAsText(fileList[0]);
}
}
else {
alert('The File APIs are not fully supported in this browser.');
}
的JSONObject印通過的console.log():
{"markers": [{"point":new GLatLng(40.266044,-74.718479), "homeTeam":"Lawrence Library","awayTeam":"LUGip","markerImage":"images/red.png","information": "Linux users group meets second Wednesday of each month.","fixture":"Wednesday 7pm","capacity":"","previousScore":""},{"point":new GLatLng(40.211600,-74.695702),"homeTeam":"Hamilton Library","awayTeam":"LUGip HW SIG","markerImage":"images/white.png","information": "Linux users can meet the first Tuesday of the month to work out harward and configuration issues.","fixture":"Tuesday 7pm","capacity":"","tv":""},{"point":new GLatLng(40.294535,-74.682012),"homeTeam":"Applebees","awayTeam":"After LUPip Mtg Spot","markerImage":"images/newcastle.png","information": "Some of us go there after the main LUGip meeting, drink brews, and talk.","fixture":"Wednesday whenever","capacity":"2 to 4 pints","tv":""},] }
「未捕獲的SyntaxError :調用JSONView()時引發意外的令牌e'。
有人可以指出代碼有什麼問題嗎?謝謝。
你在混合一個對象(這就是「json」來自的地方 - 它意味着「JavaScript Object Notation」,因爲對象是javascript本身的)和一個字符串(你不能在對象上使用'.replace')。任何不帶引號的'new'都不是有效的JSON,但它是一個有效的javascript對象。 – h2ooooooo