When making a basic JSON request, an error pops up in the JavaScript console saying "Token u was not expected"

I'm currently attempting to make a straightforward JSON call, however, I'm encountering difficulty accessing the JSON file. The console is displaying the following error message: "Uncaught SyntaxError: Unexpected token u"

Here is a snippet from my 'universe.json' file:

{"menu": {
  "key": "value",
  "object": {
    "sub_object": [
      {"key": "value", "key2": "value2"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

Furthermore, this is the content of my JS file:

$(document).ready(function(){

    var request = new XMLHttpRequest();
        request.open('GET','universe.json',true);
        request.responseType = 'JSON';
        request.onload = function() {
                    data = JSON.parse(this['menu']);
                    console.log('yes');
                };
        request.send();

});

Any guidance or assistance would be greatly appreciated. Thank you.

Answer №1

When inside the onload handler, this refers to the XMLHttpRequest instance, which does not have a menu property. Attempting to access it will result in undefined, and trying to use JSON.parse on it will turn it into a string containing "undefined", which is not valid JSON (as it starts with an unexpected u).

Since you've already set the .responseType to JSON, there's no need to parse anything. You can directly access the object.

Request.responseType = 'json'; // note the lowercase
Request.onload = function() {
    var obj = this.response; 
    // or:  = Request.response
    // or:  = JSON.parse(this.responseText); // for compatibility reasons
    var value = obj.menu;
    console.log('yes', value);
};

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

beforeprinting() and afterprinting() function counterparts for non-IE browsers

Is there a way to send information back to my database when a user prints a specific webpage, without relying on browser-specific functions like onbeforeprint() and onafterprint()? I'm open to using any combination of technologies (PHP, MySQL, JavaScr ...

Implementing an API call using Redux Saga within a React application

I have been diving into learning saga by following a tutorial on Medium and trying to implement it in StackBlitz. I encountered a path issue initially, managed to fix it after several attempts, but now a different problem has come up. Despite searching on ...

Tips for successfully passing a variable using the `request` module

I'm currently utilizing the request package to retrieve data from a JSON file. However, I am unsure of how to pass a variable. request.get('http://domain/to.json', function (error, response, body) { var json_body = JSON.parse(body); }); ...

Is there a jade plug-in available that enables manipulation using syntax similar to jQuery?

If I have a list of li elements and I want to use JavaScript to find an element with class X and modify some of its attributes, I know it can be done with regular JavaScript, but I'm unsure of how to select existing elements and manipulate them. Is th ...

What is the best way to showcase the information from this API on an HTML page using Vanilla JavaScript?

I am currently working on implementing an AJAX call to fetch data from a movie API online. Below is the HTML code I have written for this: <html> <head> <meta charset=utf-8> <title>Movie Database</title> ...

Guide to making a custom scoreboard in JavaScript for my gaming application

Being a beginner in coding, I've been working on a Battleship-like game. I've managed to do most of it, but the scoreboard isn't functioning. I'd appreciate any guidance on how to fix it or what changes are needed for it to work properl ...

Avoid triggering jQuery "change" event manually in order to prevent unintentional execution when done programm

In my invoicing system, I have implemented a feature where users can select an item using jquery select 2. Upon selection, the base price and other details are automatically filled in the form. Users also have the option to manually change this price befor ...

Nested functions in React components

I recently stumbled upon a piece of React code and I'm unsure if it's the most efficient way to do things. Below is a snippet of that code. class App extends React.Component { renderMessage = () => { function getMessage() { return ...

Activate the button in Internet Explorer 6 using Javascript

I'm facing an issue with my change password screen. It seems to work fine in IE8 and IE7, but the save button fails to enable in IE6 when the passwords match. var LblError = document.getElementById('ctl00_cphValNet_LblError'); ...

JavaScript is utilized to update HTML content through an Ajax request, but unfortunately, the styling is

Apologies for the unconventional title, I am currently in the process of creating a website. When the page is initially loaded, I call upon two scripts within the 'head' tag to create an attractive dynamic button effect. <script src="https:// ...

unable to implement multiple layouts while utilizing react-router

My current project requires two different layouts: one for the homepage (currently implemented in app.js) and another for the result page. After submitting a form, the results should be displayed in the result layout instead of the app layout. However, whe ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

What is the best method for utilizing parameters from a JSON object in view.gsp to make an image call?

I have a JSON object that I'm passing from my controller to the view, but I am having trouble accessing the individual elements of the JSON. Can anyone provide some insights on this issue? Do I need to access the JSON elements within DisplayRecentPo ...

AngularJS - Issue: [ng:areq] The 'fn' argument provided is not a function, instead it is a string

I encountered an issue: Error: [ng:areq] Argument 'fn' is not a function, received string Despite following the recommendations of others, I still have not been able to resolve the problem. Below is the code snippet in question: controller. ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

How should res.render() and res.redirect() be properly utilized within Express framework?

I am struggling to understand the difference between res.render('viewname', {msg: 'Message' }) and res.redirect('route') The render function allows you to pass a "message", but the redirect function does not. However, ther ...

Limiting jQuery searches to a specific region: Tips and tricks

If I have the code snippet below: <div class="foo"> <div> some text <div class="bar"> </div> </div> </div> <div class="foo"> <div> some text <div class="bar"> some text </div> </div> </ ...

Event handlers do not have a definition for "this"

Why is the count not defined in the increaseCounter function but is defined in the getBadgeClass function? <button onClick={this.increaseCounter} className={this.getBadgeClasses()}>Increment</button> getBadgeClasses() { ...

Unable to receive any response with AJAX requests

Welcome to my HTML page <html> <head> <title>Using AJAX</title> </head> <script type="text/javascript" src="ajax.js"></script> <body> <form action="searchItems.php" name="searchItem" method="p ...

retrieve data types from an array of object values

I am looking to extract types from an array of objects. const names = [ { name: 'Bob' }, { name: 'Jane' }, { name: 'John' }, { name: 'Mike' }, ] The desired result should resemble thi ...