JSON parsing throws an error due to encountering an 'unexpected end of input' issue

Here's some code I'm working with:

var default_links = 
'{ "name" : "Google",    "url": "https://encrypted.google.com/", "fav_url": "https://encrypted.google.com/favicon.ico" }\n'+
'{ "name" : "Yahoo",     "url": "http://www.yahoo.com/",         "fav_url": "http://www.yahoo.com/favicon.ico" }\n'+
'{ "name" : "GMail",     "url": "https://mail.google.com/",      "fav_url": "https://mail.google.com/favicon.ico" }\n'+
'{ "name" : "Twitter",   "url": "https://www.twitter.com/",      "fav_url": "https://www.twitter.com/favicon.ico" }\n'+
'{ "name" : "Facebook",  "url": "https://www.facebook.com/",     "fav_url": "https://www.facebook.com/favicon.ico" }\n'+
'{ "name" : "Wikipedia", "url": "https://en.wikipedia.org/",     "fav_url": "http://en.wikipedia.com/favicon.ico" }\n';

function write_links()
{
    var linkdata = default_links.split("\n");
    for (i = 0; i < linkdata.length; i++)
    {
        var link = JSON.parse(linkdata[i]);
        document.getElementById("useful_links").innerHTML += '<a href=\"' + link.url + '"><img src="' + link.fav_url + '">' + link.name + '</a><br>';
    }
}

After parsing all the lines, an error shows up:

[xx:xx:xx.xxx] SyntaxError: JSON.parse: unexpected end of data @ http://127.0.0.1/homepage.html:33

What might be causing this issue?

(Yes, I know the design isn't great with splitting by \n, but it's a temporary solution for specific undisclosed issues.)

Answer №1

There appears to be a line break at the conclusion of your most recent input. This results in an empty string as the final element when separating by lines, which renders it incompatible with JSON formatting.

Answer №2

 for (let index = 0; index < linkdata.length - 1; index++) 

Include -1 in the for loop condition to prevent errors caused by creating an empty array when splitting with newline. If the last loop runs, it will throw an error since we cannot parse an empty string. Alternatively, remove the last newline string from default_links.

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

Ordering results of Python script by location and grouping by shared identifier

There are numerous occurrences of data sharing the same location IDs, like in the output below where '3' is repeated multiple times: 121 {'data': {'id': 3, 'type': 'location'}, 'links': {&ap ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Looking to tally up the rows in a joined table using Sequelize?

In my current project, I am utilizing the sequelize library to interact with a sqlserver database. The database consists of two tables: data: columns - id, name, team, type history:columns - id, node, date, status, data_id (foreignkey) In terms of their ...

What is the command line method for running ESLint in flat configuration?

When using the flat config for eslint.config.js, how can I lint *.js files recursively from the command line? 1 In the past with eslintrc.js or eslintrc.json, I have used npx eslint . --ext .js, as mentioned here. Up until now, it has always worked withou ...

Dynamic scope variables in AngularJS are powerful tools that allow you

I am currently working with a scope variable called jsonData which looks like this: $scope.jsonData={id:'1234',abcd:{array:[{a:'data',b:'bdata',c:'cdata'},{a2:'a2data',b2:'b2data',c2:'c2data ...

My code gets disrupted when I switch between ids and classes

I'm currently learning about javascript and jquery, attempting to implement various scripts. I successfully executed the following script: jQuery(document).ready(function($) { var scroll_start = 0; var startchange = $('#homepage-header' ...

Encountering TS 2732 error while attempting to incorporate JSON into Typescript

Having trouble importing a JSON file into my TypeScript program, I keep getting error TS2732: Can't find module. The JSON file I'm trying to import is located in the src folder alongside the main.ts file. Here's my code: import logs = requi ...

The JSON parsing encountered an error: Domain=NSCocoaErrorDomain Code=3840 "Failed to complete the operation. (Cocoa error 3840.)"

Currently, I am using the sendAsynchronousRequest request method to communicate with the server and retrieve data from it. Oddly enough, when I test the web service in a browser, everything seems to be functioning correctly and I receive the expected respo ...

What are the steps to successfully install OpenCV (javascript edition) on Internet Explorer 11?

I'm currently experiencing issues with getting the OpenCV javascript version to function properly on IE11 for contour detection. While my code runs smoothly on all other up-to-date browsers, I am encountering errors such as: TypeError: Object doesn&a ...

Experience the latest HTML5 features directly within a Java desktop GUI, with seamless communication through

This Java desktop GUI utilizes a Java-based web services communication layer along with an HTML library to provide powerful charting and interactivity. I am looking to integrate an HTML5 view within the Java GUI. Can someone assist me in managing JavaScri ...

Tips for correctly adding a JSON output to a dropdown menu option

What is the correct way to add JSON results to a select option? Here is a sample of JSON data. AJAX code example: $.ajax({ url: 'sessions.php', type: 'post', datatype: 'json', data: { from: $ ...

Refresh the content with an embedded iframe

I am attempting to update the body content by removing all existing content and inserting an iframe: function create_custom_iframe(target){ var iframe = document.createElement('iframe'); iframe.setAttribute('id', 'target_u ...

Ajax - Trouble with Updating DIV Content

As a beginner in AJAX, I am encountering difficulties creating a simple AJAX program. My goal is to have a button that, when clicked, changes the text of the div below it. Despite numerous attempts, I have not been able to identify the issue. Below is the ...

Add the value to an ObjectNode and then retrieve a JsonNode from the Jackson JSON library

I am struggling to add a value to a json object in the specified format and then store it in the database. { "mainObject": { "childObject1": { "validator": { "dataType": "TEXT", ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

Loading screen for specific content within the current WordPress theme

I am trying to display a preloader only in the 'content' div, but it ends up hiding the entire page. The structure of the site is as follows: Title Menu Content (where I want the preloader) Footer I'm having trouble figuring out where exa ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...