Oops! An unexpected error occurred while parsing the JSON response

While working with my Json file, I encountered an error that has been validated on https://jsonlint.com/

@Injectable()
export class LightParserService{
  ITEMS_URL = "./lights.json";
  constructor(private http: Http) {
  }

  getItems(): Promise<Light[]> {
    return this.http.get(this.ITEMS_URL).toPromise()
    .then(resp  => {
        return resp.json() as Light[];
      });
    }
}

However, when I try to use my function in another component:

lights : Light[] = [];
getLights(): void{
      this.lightService.getItems().then(light => this.lights = light);
    }

Upon visiting my website, I am faced with the following error message: Error: Uncaught (in promise): SyntaxError: Unexpected token < in JSON at position 0

I am perplexed by this issue. The JSON file is valid and the fields in my Light object are correct. Can someone help me resolve this?

Answer №1

./lights.json likely provided HTML instead of JSON, causing the failure of your resp.json() function. To troubleshoot this issue, you can insert console.log(resp.text()) right before the line return resp.json() as Light[];. This will allow you to view the raw response directly (alternatively, you can look it up in the developer tools networking tab).

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

What is the best method to select pagination in a Spring Boot application?

I am seeking advice on implementing pagination for my table data in a Spring Boot application. The dataset is quite long, so I have implemented pagination to retrieve the data from the database efficiently. Currently, I have a REST method in my Spring Boo ...

Seamless Axios operations even without internet connection in Vue.js

In my Nativescript Vue.js application, there is a functionality where the user clicks on login, Axios makes a call to an endpoint to fetch a token. However, I noticed that when the emulator phone is offline, the Axios call still goes through and the &apos ...

Is it possible to utilize the Substring() method on JSON data retrieved from an API?

I have been working with a timezone API that provides the time from a specific city in this format: 2019-10-26 15:30. I want to display only the time on my page, but currently it shows the full date as well, which is not what I desire. This is my first ex ...

bootstrap used for creating horizontal radio buttons

I'm attempting to horizontally align radio buttons within a form without relying on the Bootstrap library. The following code achieves this: <form id="test_form"> <div class="control-group"> <label for="Q1">First question</ ...

Having trouble getting the Lightbox video Gallery to function properly in Bootstrap

When building my website with bootstrap 4, I incorporated image and video galleries. To create a lightbox effect, I referenced . My CSS and jQuery script are implemented at the end of the body. The image gallery functions perfectly, indicating that the im ...

Moving DOM Elements around

Objective: Looking to relocate an element within the DOM structure. Condition: Although I am familiar with using jQuery for this task, I am currently working in an environment without access to it. Therefore, I need a pure JavaScript solution. Example: ...

There was an unexpected error encountered while trying to use Jade

I encountered an error in my jade template: Error: E:\Do\hello_express\node_notes\views\simple.jade:6 4| meta(charset="utf-8") 5| meta(name="viewport",content="width=device-width,initial-scale=1,maximum-scal ...

Navigating Angular 2 v3 router - accessing the parent route parameters within a child route

My route is configured as /abc/:id/xyz The abc/:id portion directs to ComponentA, with /xyz being a nested component displayed within a router-outlet (ComponentB) Upon navigating to /abc/:id/xyz, I utilize this.route.params.subscribe(...) (where route is ...

Is it possible to correlate the position of a medical image segment with the position of a mouse click event in JavaScript?

Greetings and thank you for taking the time to read this! This query is closely linked to the following library: https://github.com/FNNDSC/ami I am interested in developing a function that can detect when a user clicks on a segment within an image, trigg ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

Troubleshooting issues with Ajax and Jena

Whenever I attempt to utilize AJAX to call Jena in my servlet, I encounter this error: java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apa ...

How can I transfer an array from a servlet to HTML using jQuery?

As I parse an uploaded XML file with the dom, the generated string combines the hostname and osname values separated by a , delimiter. The variable s holds this string which is then sent back to HTML using the response.getWriter object obj. However, instea ...

Activate the Flexslider when it comes into view

Currently using flexslider, I am attempting to create a smooth transition from the second slide back to the first as soon as the slider is in view. My initial idea was to implement if (scroll >= 500px && scroll < 600px) however, I am uncerta ...

The Jest worker has run into 4 child process errors, surpassing the maximum retry threshold

I am a newcomer to Vue and Jest testing, and I keep encountering this error when running a specific test. While I understand that this is a common issue, I am struggling to pinpoint the exact cause of the problem. Here is the error message: Test suite fa ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

What is the syntax for implementing React.forwardRef in a dynamic Anchor or Button component?

I am working on a component that can act as either a button or an anchor tag. However, I am facing challenges in implementing conditional typing for the ref. How can I resolve this issue and make the ref acceptable? type ConditionalElements = | ({ ...

Organize by the quantity of elements in an array using mongoose and MongoDB

Within my Post model, I have an array called likes that contains the ObjectId of users who liked the Post. My goal is to sort Posts based on the number of likes they have received. I've experimented with using $size, $sort, and aggregate, but so far ...

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

Pass PHP date to JavaScript and increase its value

I'm looking to retrieve the server time with PHP and store it in a JavaScript variable. Once stored, I'd like it to continuously increment. Below is the code snippet: function initTime(date){ var today=new Date(date); var h=today.getHours(); v ...

What is the reason behind only being able to toggle half of the element's classes?

My current project involves using jQuery's .toggleClass() function to implement a favorite button within multiple <div> elements, each containing an <a> element and an <i> element. I am toggling between two Font Awesome icons by swit ...