我有来自服务器的内容,我正在下载到文件中,所以当我有多行json我无法下载文件我得到意外的令牌我相信这个例外是因为新行字符,我该如何解决这个问题?
来自服务器的数据
{"level":"info","message":"Test Log messages"}
{"level":"info","message":"Test Log messages"}
{"level":"info","message":"Test Log messages"}
ctrl.js
$scope.downloadFile = function(message){
DitFactory.getFile(message).then(function(response,$window){
var data = JSON.stringify(response.data);
var blob = new Blob([data], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(blob, 'text.txt');
console.log(response);
});
};
错误
angular.js:13708 SyntaxError: Unexpected token { in JSON at position 49
at Object.parse (native)
at fromJson
答案 0 :(得分:2)
有效的json响应应如下所示:
[
{"level":"info","message":"Test Log messages"},
{"level":"info","message":"Test Log messages"},
{"level":"info","message":"Test Log messages"}
]
更改服务器响应以返回有效值。
否则,如果这样,则解析响应如下:
var response = '{"level":"info","message":"Test Log messages"}\n{"level":"info","message":"Test Log messages"}\n{"level":"info","message":"Test Log messages"}';
var items = response.split('\n');
items = items.filter(function(item) {
return item
})
.map(function(item) {
return angular.fromJson(item);
});
console.log(items);