Challenges when Accessing JSON Documents

Currently, I'm working on a webpage project where I needed to access a JSON file in my JavaScript code. Here's the script I wrote for that purpose:


        function xhrSuccess () { this.callback.apply(this, this.arguments); }
        function xhrError () { console.error(this.statusText); }

        function loadFile(url) {
            var request = new XMLHttpRequest();
            request.callback = readJSON;
            request.onload = xhrSuccess;
            request.onerror = xhrError;
            request.open("GET", url, true);
            request.send(null);
            return request.callback();
        }

        function readJSON() {
            console.log(this.responseText);
            var myJsonObj = JSON.parse(this.responseText);
            return myJsonObj;
        }
    

This is how I call the function:

var jsonData = loadFile("http://localhost:8000/json/data.json");

But unfortunately, I keep encountering some errors and I am quite puzzled as to why they are happening.


        Uncaught SyntaxError: Unexpected end of input
        Uncaught SyntaxError: Unexpected token :
    

The first error seems to occur during the JSON parsing process.

I'm struggling to understand the exact meaning of these errors as they typically indicate syntax-related issues like missing semicolons or incorrectly formatted objects. However, since the error is being triggered at the JSON.parse() line, I'm unsure about what could be causing it.

If anyone could provide some guidance, it would be greatly appreciated.

Also, here's the JSON data I'm trying to parse:

{ "data": [
         {"file": "temp", "title": "This is a test", "date": "August 21, 2015"},
         {"file": "temp2", "title": "This is also a test", "date": "August 20, 2015"},
        {"file": "temp3", "title": "This is the final test", "date": "August 22, 2015"}
    ] }
    

Answer №1

When attempting to parse a JSON object that has not been stringified, it can result in encountering Unexpected token errors. It's important to verify that the JSON content being received is indeed stringified.

In the provided code snippet, there is an issue with returning oReq.callback(); within the loadFile function. Upon later calling loadFile (

var data = loadFile("http://localhost:8000/json/data.json");
), the line return oReq.callback(); gets executed immediately, causing the value of this.responseText to be an empty string ("") by the time readJSON is triggered. This leads to errors like "Unexpected end of input" since JSON.parse('') throws such an error.

An alternative approach involves processing the data directly within the readJSON function after the asynchronous request is resolved. However, this method may result in poor code quality when dealing with subsequent requests. Here's an example showcasing callback chaining:

// Example of Callback Chaining
var xhr1 = new XMLHttpRequest();
xhr1.onload = function (req) {
  var data = JSON.parse(req.responseText);
  var postId = data.posts[0].id;

  // Nested XMLHttpRequests might lead to the Pyramid of Doom.
};
xhr1.open('GET', 'http://example.com/users/1', true);
xhr1.send();

The aforementioned structure is known as "the Pyramid of Doom." Modern solutions like Promises offer enhanced ways of handling the mentioned use cases. While Promises are part of ES6/ES2015 specification and not universally supported by browsers, polyfills or libraries like jQuery's $.ajax and AngularJS's $q can bridge this gap.

To utilize the babel-polyfill from Babel, first include the polyfills before your JS code via a cdnjs.com link:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js"></script>

The updated code utilizing promises:

// Code using Promises
function loadData(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();

    xhr.onload = function onload(request) {
      if (request.status >= 200 && request.status < 400) {
        var data = JSON.parse(request.responseText);
        resolve(data);
      } else {
        reject(Error('Could not load any data'));
      }
    };
    xhr.onerror = function onerror(err) {
      reject(err);
    };

    xhr.open("GET", url, true);
    xhr.send();
  });
}

// Handling promise resolutions and rejections
loadData('http://example.com')
  .then(function (data) {
    console.log('Got the data!', data);
    return JSON.parse(data);
  }, function (err) {
    console.log('There was an error', err);
  })
  .then(function (parsedJson) {
    console.log('Parsed JSON', parsedJson);
  });

Link to thePlunker demo.

For further learning about asynchronous requests and promises, numerous guides and tutorials are available online! 😉

Answer №2

When an uncaught SyntaxError occurs, it indicates that the JSON being parsed is not correctly formatted.

Have you established a setting for this.responseText? It may be more appropriate to utilize sMsg.responseText instead. Adding additional context in your question could help clarify this issue further.

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

Tips on customizing Google Analytics code with Google Tag Manager

My website is currently equipped with the Google Analytics tracking code implemented through Google Tag Manager. The standard Google Analytics code typically appears as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']= ...

What is the best way to retrieve information from two tables in SQL server with the help of AngularJS?

Seeking assistance as I navigate the process of extracting data from two tables within the same SQL Server database. My goal is to incorporate this data into an HTML table, utilizing a JavaScript script to access information from one table (Table1). Below ...

What is preventing me from retrieving the element of a vector in an array using array[i].x?

Why do I keep encountering this Error: Cannot read properties of undefined (reading 'x') let array = []; let vector = new THREE.Vector3(2,3,2); array.push(vector); console.log(array[-1].x); ...

Guide for displaying and hiding an image using a button or link in Next.js

I'm a beginner with React and Next.js, and I have the following code snippet: import Link from 'next/link'; import Image from 'next/image'; async function getPokedex() { const response = await fetch(`http://localhost:3000/api/p ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

Is it possible to engage with a local webpage using an application and receive real-time feedback?

I am interested in finding a way to connect my local HTML page with my C++ application. Similar to using the JavaScript console to make real-time edits to a webpage, like this: document.getElementById('divlayer').style.visibility = 'hidden& ...

`There is a challenge with parsing JSON in an iPhone app`

I'm encountering a problem where my application crashes every time I try to submit. Any insights on how to fix this issue? 2011-08-09 19:41:29.590 ItcHotel[3888:207] made it to the didReceiveData function 2011-08-09 19:41:29.593 ItcHotel[3888:207] * ...

Searching through JSON information from a collection with C# UWP

string Categoriesjson = @"[ { 'cat_id' : 1, 'name': 'HTML', 'desc': 'WebDesign', &ap ...

Why isn't data displaying in the AJAX RESTful client for Java?

I have created an HTML form that is supposed to display the only user I have in JSON format in an alert box when a button is pressed. However, it currently shows an empty JSON body. I have checked the REST class and the URL in the AJAX call, both of which ...

How can I correctly export my npm package?

I have successfully developed an npm package. class Person { constructor() {} sayHello() {console.log("Hello World!")} } module.exports = Person; Upon installing the package using npm i my-package, it was integrated into my project. ...

Steps for creating a file selection feature in Chonky.js

I recently integrated the Chonky library into my application to build a file explorer feature. One challenge I am facing is figuring out how to select a file and retrieve its unique ID when the user double clicks on it. const [files, setFiles] ...

Incorporate additional plugins into React-Leaflet for enhanced functionality

I'm currently working on developing a custom component using react-leaflet v2, where I aim to extend a leaflet plugin known as EdgeMarker. Unfortunately, the documentation provided lacks sufficient details on how to accomplish this task. In response, ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

Having trouble with sending a post using ajax? Addressing the bad request issue

Hey there! I'm just dipping my toes into the world of API and could really use some guidance... So, here's the code snippet I've been working on: <!DOCTYPE html> <html> <head> <title></title> <script src ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

What's preventing access to class property in TypeScript when using asynchronous methods?

Consider the following TypeScript class: class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } thisworks(input) { console.log("I am " + input) ; ...

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

Ways to send a variable to a component through history.replace

Is there a way to retrieve the match.chatroomId in a functional component? I am currently using history.replace to navigate to this component. Here is the code snippet: onClick = {() => history.replace(`/chat/${match.chatroomId}`)} ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

What is the best way to incorporate an ASYNC function within a .map function to dynamically populate a table in a REACT application?

I am attempting to use the .map() method in REACT to call an async function and populate table data cells. The async function communicates with the backend of my application using data from the array being looped through. When called correctly, the functi ...