Dealing with an unexpected token error in JSON when faced with two lines

When downloading content from the server into a file and dealing with multiple lines of JSON, an unexpected token error occurs due to new line characters. How can this issue be resolved?

Data from the 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 №1

To ensure your JSON response is valid, it should follow this format:

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

Please adjust your server response accordingly to match the valid format.

Alternatively, if needed, you can parse the response in the following way:

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

Check out this Online Demo: https://plnkr.co/edit/H3tcxWqMUFep4n3LSt1C?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Jquery-steps to Dynamically Activate ng-messages Validation Through Controller JavaScript Functions

I am working on a form that utilizes the ng-messages validation system and is structured into different sections using jquery-steps. My goal is to activate the validation process when a user moves from one section to another by clicking on the jquery-step ...

An error occurs when trying to cast a JSONArray into a java.util.ArrayList

I am currently working on an Adapter class that includes a Filter, and I encountered an error in the publishResults method. The list loads fine, and filtering works when typing into the filter. However, the app crashes with an error when deleting character ...

Is the injector giving back a value of undefined?

Having an issue with my legacy code where injector() is returning undefined. Check out this plnkr for more details. Furthermore, I am wondering if updating a property value in the service will automatically reflect in the scope without needing to use ...

What is the best way to terminate a "for await ...of" loop if it fails to finish within a specified timeframe?

Is it possible to stop an asynchronous loop if it doesn't finish within a set time frame? I'm working with the following code: (async()=>{ for await(let t of asynDataStreamOrGenerator){ //some data processing } //some other code I n ...

Exploring the near method to Parse.Query a class

I'm currently working on my first iOS application, which allows users to add annotations to a map for others to view. In this project, I have decided to utilize Parse as the backend service. What I already have: There is a class called "Pins" in Par ...

Record details to text file after the button is clicked on ASP.NET

My goal is to save an integer value (incremented each time a button is pressed) into a .txt file for each individual. However, I am struggling with how to store the value of each person's button click. I have a method in mind, but I need assistance wi ...

A simple method to obtain the ID of the element that has been clicked and save it in a variable to be utilized in a function responsible for

Seeking assistance in optimizing the code below by removing the specific #static id and allowing for dynamic IDs such as #dynamic within the one click function. This would eliminate the need to repeatedly copy and paste the same function with different ID ...

Looking to conceal the edges of a ThreeJS box primitive

I'm trying to figure out how to hide the edges displayed in a box primitive using ThreeJS. The edges only appear when I apply a texture to the faces. I've attempted various options such as setting wireframe=false, but the edges persist. Here&ap ...

The process of transferring information from a JSON API to TypeScript models

When working with my JSON API in my services, I need to pass the data to my models. What is the most efficient way to accomplish this task? Currently, I am following this process: import { Attachment } from '.'; export class Contact { id: nu ...

Running various IT blocks within a Protractor loop to enhance web testing

After logging in to a web page, we need to use a for loop to perform multiple tests on the page. The ideal test scenario involves a table with buttons on each row that leads to another page where data needs to be validated. Currently, all expectations and ...

The GeoChart zoomOut button is not visible at this time

I am currently exploring the geochart API, which is a relatively new one with limited information available. <!DOCTYPE html> <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></scr ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

Following the modifications made to the JSON file using Groovy, the file now includes additional curly brackets and a "content" object within the data

Within my json file, I have the following data: {"globals":{"code":"1111","country_code":"8888","hits":80,"extra_hit":1,"keep_money":true},"time_window":{"from& ...

AngularJS allows you to add a required attribute to an input tag, which will

When incorporating the required field or email validation on the input tag in AngularJS, a tooltip appears. I am looking to eliminate this tooltip while utilizing Bootstrap. Any suggestions on how to achieve this? ...

What could be causing my 3D Model to fail to load in three.js when using the glTF loader?

I'm trying to load a 3D object into my three.js project for the first time. I have the object downloaded on my computer and have connected the three.js library and the glTF loader to my HTML document. However, every time I run the code, I encounter th ...

Unable to retrieve React state within the callback function

As I work with the following components: const ParentComponent: React.FC = () => { // Setting newType to some value within the code const [newType, setNewType] = useState<any>(undefined); // Enabling addEdge to true in another part o ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

What is the best way to ensure that the value of a <textarea> in jQuery is consistently saved and reflected in the HTML document?

I have a function on my website that allows users to input text which is then displayed on the page. However, this text disappears when the page is reloaded and does not stay permanently. How can I use jQuery to make sure that the entered text remains on ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

Issue with a straightforward jQuery Templates illustration

Utilizing jquery-tmpl, I am working with the following JSON data for form validation in ASP.NET MVC3: {"Status":1,"Message":"Oh dear, what have you done. Check the list of errors dude!","Errors":["The Contents field is required.","The Date Created field i ...