hussain hussain - 5 months ago 15
AngularJS Question

How to resolve unexpected token error when you have two lines in json?

I have content from server that i am downloading into file, so when i have multiple lines json i could not download the file i am getting unexpected token i believe this exception is because of new line character, How can i resolve this issue ?

data from server

{"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);
});
};


error

angular.js:13708 SyntaxError: Unexpected token { in JSON at position 49
at Object.parse (native)
at fromJson

Answer

Valid json response should look like this:

[
    {"level":"info","message":"Test Log  messages"},
    {"level":"info","message":"Test Log  messages"},
    {"level":"info","message":"Test Log  messages"}
]

Change your server response to return valid value.

Otherwise, parse the response like this if this:

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);

Online Demo - https://plnkr.co/edit/H3tcxWqMUFep4n3LSt1C?p=preview