hussain hussain - 1 year ago 46
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"}


$scope.downloadFile = function(message){
var data = JSON.stringify(;
var blob = new Blob([data], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(blob, 'text.txt');


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

Answer Source

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


Online Demo -