Encountering a syntax error when trying to parse a local storage object?

I've been exploring ways to store random numbers generated by Math.random. I've come up with a solution where I save the numbers in an array, which is then stored in localStorage. My goal is to append each new array of numbers whenever Math.random is used. To see the code I attempted to write, you can check it out here.

var nums = [];
for (var i = 0; i < 5; i++) {
    var num = Math.floor(Math.random() * 50);
    nums.push(" " + num);
}
console.log(nums);

function appendToStorage(name, data) {
    var old = localStorage.getItem(name);
    if (old === null) old = "";
    localStorage.setItem(name, old + JSON.stringify(data));
}

if (localStorage.num) {
    appendToStorage('num', nums);
} else {
    localStorage.setItem("num", JSON.stringify(nums));
}
var nums2 = localStorage.getItem("num");
console.log(nums2);
document.getElementById("test").innerHTML = JSON.parse(nums2);

Unfortunately, this setup doesn't seem to be functioning correctly. The console shows an error message saying

Uncaught SyntaxError: Unexpected token [
. This issue seems to be resolved if I remove the JSON.parse from the getElementById. However, I prefer to keep it parsed so that the numbers are displayed more clearly. Any suggestions on how I can resolve this?

Answer №1

If you concatenate a valid JSON string with another valid JSON string, the result will not be a valid JSON string. For instance:

var myJSON = '{"thing": "data"}';  // valid
myJSON = myJSON + myJSON; // myJSON now becomes '{"thing": "data"}{"thing": "data"}', which is not valid

To ensure accuracy, you must parse the retrieved JSON data, make the necessary updates, and then stringify it again before saving it in localStorage.

function appendToStorage(name, data) {
    var old = localStorage.getItem(name);
    if (old === null) old = "[]";
    var newData = JSON.parse(old);
    newData.push(data);
    localStorage.setItem(name, JSON.stringify(newData));
}

Keep in mind that parsing the data will return an array, causing issues when setting the innerHTML. You'll need to convert the array into a text format first (credit goes to jibsales for this insight).

Answer №2

To assign a string as input to Element.innerHTML, avoid using an Array. Consider utilizing JSON.parse(nums).join("");

Implementing this technique enables you to exclude the initial white space in your loop and include it at the beginning of the Array.join method. For separate lines for each number, specify "\n".

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

To achieve proper display of multiple boxes, it is essential for each box to be

My current approach involves adding boxes to the scene based on specific dimensions for height, width, and depth, and it works perfectly when the boxes are all square. https://i.sstatic.net/HdDSX.png However, the issue arises when I try to use a rectangu ...

Using Ajax to preview images results in displaying a broken image icon

I am currently working on implementing an image preview function using Ajax. As I was experimenting, a couple of questions came to my mind: Once the Ajax has been executed, is the actual image uploaded to the server or just an array containing strings l ...

Using React hook form to create a Field Array within a Dialog component in Material UI

I have a form with custom fields added via Field Array from react-hook-form, and everything is functioning properly. However, I recently implemented drag and drop functionality for the property items to allow reordering them. Due to the large number of fie ...

Warning: Attempting to access a property of an invalid object in

I've been diving into PHP recently. I expected it to output 0, but oddly enough I received an error message: Notice: Trying to access property of non-object in... <?php $json = '[{"assetref":"","qty":0,"raw":0}]'; $obj = json_deco ...

The absence of a backslash in the JSON string is noticed upon uploading it to the database

After using the JSON.stringify() method in JavaScript to convert my JSON object into a JSON string, I insert it into a database via AJAX posting to a PHP file. $("#saveToDatabase").click(function(){ var place = searchBox.getPlaces(); var locati ...

Enhancing Json_Encode output with extra arrays

I'm facing some challenges with the json_encode output. To enhance the speed of our extensive dropdown navigation menu, I decided to store all the data in a json file that is updated daily and retrieved as needed. When generating the json using json_ ...

What steps should I follow to generate a JSON object and apply it to refresh an ng-repeat?

Struggling to work this out. I am aiming to craft a JSON object and then utilize it to enhance my ng-repeat (specifically, prepend the ng-repeat with the information contained in the JSON object). Presented below is my code: Javascript: var data1 = &apos ...

Troubleshooting Vue.js: Why is .bind(this) not behaving as anticipated?

Demo: https://codesandbox.io/s/23959y5wnp I have a function being passed down and I'm trying to rebind the this by using .bind(this) on the function. However, the data that is returned still refers to the original component. What could I be missing h ...

Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead o ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

How to utilize "json_encode" function for accessing array elements

I'm currently working on fetching a JSON request from the query string ID, and it seems to be functioning almost correctly. However, an additional array object is being added. $id = $_GET['id']; $result = mysqli_query($con,'SELECT * F ...

The "flickering" effect of the div is like a dance, moving gracefully between fade outs and

I am encountering a similar issue as described in this thread: same problem (fiddle: original fiddle). However, I am still learning JavaScript and struggling to apply the solution provided because my HTML code is slightly different. Can someone please assi ...

Using Python 3.6 to extract data from a JSON response containing nested dictionaries

My mind is in a whirl because I can't seem to properly interpret this response in JSON format. I've attempted various methods but none seem to work as desired. Can you lend me a hand? Here's the file I'm trying to parse: { "info": ...

Navigating a JSON array using the Handlebars template engine

I have a JSON file and I am looking for guidance on how to display the information from it using the handlebars template engine: This is the template code: <script id="template-app" type="text/x-handlebars-template"> {{#each data}} Emai ...

Using react-big-calendar exclusively for the month view

I need help customizing react-big-calendar to only show the month view and trigger a function when a date is selected. I want to remove all other functionalities related to week, day, agenda, and time display. Essentially, I just want to display the month- ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

I am facing website crashes when using the FindOneAndUpdate method in Node.js with MongoDB due to events.js issue

I'm experiencing issues deleting an array index with an ID obtained from the front-end. Although my code successfully deletes the elements, it causes the website to crash, leading me to restart npm or check Mongo's Atlas for results. I feel quite ...

The array is failing to pass through ajax requests

Here is the JavaScript code snippet for making an AJAX call. In this scenario, the code variable is used to store a C program code and then pass it on to the compiler.php page. function insert(){ var code = document.getElementById("file_cont").val ...

What is the process of serializing a list in Python?

When faced with the challenge of serializing a list that contains timestamp and other attributes which json.dumps cannot handle, I decided to create my own custom serializer. After researching on Stack Overflow, I found a solution: class PythonObjectEncod ...

Using Django to load a template and incorporate a loading spinner to enhance user experience during data retrieval

In my Django project, I need to load body.html first and then dashboard.html. The dashboard.html file is heavy as it works with python dataframes within the script tag. So, my goal is to display body.html first, and once it's rendered, show a loading ...