Javascript and JSON: Making Updates to Files

Working on a program, I am faced with an issue while sending a literal variable to local storage using JSON.stringify. My goal is to continuously update the local storage and append to the existing data stored. The problem arises during the parsing of the JSON file. Here's the code snippet I've been using to add to the storage:

function addtoStorage(key, data) {
    if (typeof(Storage) !== "undefined") {
        if (localStorage[key]) {
            console.log("Local Storage data: " + localStorage[key]);
            var olddata = JSON.parse(localStorage[key]);
            var dataJSON = JSON.stringify(olddata + data);
            localStorage[key] = localStorage[key] + dataJSON;
        }
        else {
            var dataJSON = JSON.stringify(data);
            localStorage[key] = dataJSON;
        }
    }
    else {
        console.log("Unfortunately, your browser does not support storage capabilities. Please upgrade for better performance.");
    }
}

}

The output displayed through console.log is as follows:

Local Storage data{"asdf":"","tes":6,"type":"asdf","ast":1,"sd":"","ew":"","asdf":{"te":0,"wer":0},"asf":"","te":"","context":{"asdf":1,"total_hits":0,"asdf":1,"tew":0,"asdf":"","tes":"","date":"asfd-asdf-","asdf":0},"asdf":""}"[object Object][object Object]" main.js:487

Uncaught SyntaxError: Unexpected string

I believe I have identified the issue causing this error. However, I am struggling to find the solution to it. It seems like the JSON object is being closed prematurely, any suggestions on how I could rectify this problem???

Answer №1

Instead of simply adding olddata + data, consider creating a custom object merge function to combine the two objects. The purpose of stringify is to convert JavaScript objects to JSON, so direct addition will not work.

You can try using a merge function similar to the one used in jQuery:

function mergeObjects(firstObj, secondObj) {
    var length = +secondObj.length,
        j = 0,
        i = firstObj.length;

    for (; j < length; j++) {
        firstObj[i++] = secondObj[j];
    }

    firstObj.length = i;

    return firstObj;
}

Then you can merge the objects and stringify the result like this:

var mergedData = mergeObjects(olddata, data);
var jsonData = JSON.stringify(mergedData);

For reference, check out jQuery's core.js file at https://github.com/jquery/jquery/blob/master/src/core.js#L390.

Answer №2

A syntax error that was not caught, caused by an unexpected string
, originates from the JSON.parse function when attempting to parse invalid JSON data (http://json.org/)

The issue arises from adding an object to another object, resulting in a string instead of valid JSON data

Subsequently, when trying to convert it using stringify, the entire structure gets treated as a single string on the initial and subsequent attempts. The process seems fine initially but fails during parsing at a later stage due to mixing a JSON object with a string.

If your aim is to store solely JSON objects, consider utilizing jQuery's extend feature (http://api.jquery.com/jQuery.extend/)

Alternatively, if you need to store various data types beyond objects, consider converting everything into an array format

This approach should address all related concerns

function addtoStorage(key, data) {
    if (typeof(Storage) !== "undefined") {
        if (localStorage.getItem(key)) {
            console.log("Local Storage data: " + localStorage.getItem(key));
            var olddata = JSON.parse(localStorage.getItem(key));
            var newdata = null;
            if(olddata instanceof Array){
                olddata.push(data);
                newdata = olddata;
            }else if(data instanceof Array || !(data instanceof Object) || !(olddata instanceof Object)){
                newdata = [olddata, data];
            }else if(data instanceof Object && olddata instanceof Object){
                newdata = $.extend(olddata, data);
            }
            var dataJSON = JSON.stringify(newdata);
            localStorage.setItem(key, dataJSON);
        }
        else {
            var dataJSON = JSON.stringify(data);
            localStorage.setItem(key, dataJSON);
        }
    }
    else {
        console.log("Your browser lacks storage capabilities. Consider upgrading for better performance.");
    }
}

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

Enhance the appearance of TreeGrid nodes by customizing the icons according to the data within

Currently, I am working with the MUI DataGridPro component and my goal is to customize the icons of the TreeGrid nodes based on the data. This image illustrates what I hope to achieve: https://i.stack.imgur.com/nMxy9.png Despite consulting the official do ...

Can you increase all px measurements in Notepad++ by a factor of X?

Looking for help with a large HTML image map that contains over 3000 lines of images with specific top/left pixel positions. I'd like to replace these images with larger ones, which would require increasing all the pixel references by a certain amount ...

The offsetTop property of Angular's nativeElement always returns a value of 0

I am currently working on a menu that will automatically select the current section upon scrolling. However, I am running into an issue where I am consistently getting a value of 0 for the offsetTop of the elements. The parentElement returns a value for of ...

Refreshing JSON data in AngularJS: How to update only the changed content in an ivh-tree using REST API

After making a REST API call to fetch JSON data in tree format, I save it in a scope variable called $scope.treeData[]. This data is then displayed in an ivh-tree. To keep the data up to date, I use an interval to update it every 60 seconds. The issue ar ...

Steps for interacting with a button of the <input> tag in Selenium using Python

As I attempt to complete a form submission, I encounter an issue where clicking the submit button does not produce any action. It seems that the problem lies with the button being tagged as <input>: <input type="submit" name="submit ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

I have successfully implemented the Context API in my Next.js project and everything is functioning smoothly. However, I encountered an error while using TypeScript

Currently, I am working on a Next.js project that involves using the Context API. The data fetched from the Context API works perfectly fine, but I am encountering errors with TypeScript and I'm not sure how to resolve them. Error: Property openDialo ...

Advantages of placing script src tags at the top of the body versus placing them at the bottom of the body

I've heard that it's best to place the script tags right before the closing body tag. However, when I follow this advice, my angularJS expressions don't seem to compute correctly for some reason. When I place the script tags in that location ...

Send the ID of the checkbox to a PHP file using AJAX

Is it possible to generate a network graph by selecting checkboxes? When I choose one or more checkboxes and click the button, I expect to see a network graph with the selected checkboxes. It almost works, but when I select multiple checkboxes, only one ...

What is the best way to eliminate extraneous object labels from the String of a JSONArray?

I am working with a JSONArray in String format that looks like this: { "productsList": [{ "map": { "productSubcategory": "Levensverzekering", "nameFirstInsured": "Akkerman" } }, { ...

Received an error while attempting an AJAX GET request to a distinct server hosting a WebAPI

This is my first time encountering an issue with an Ajax request in client-side code. I'm hoping that there's a simple mistake in my code that I'm just overlooking. Just to give some background, when I manually access the URL mentioned below ...

How can I take photos in bulk when I open the camera on Ionic 3?

Is there a way to capture multiple images at once using the camera? Currently, I am only able to capture one image when the user clicks. However, I would like to capture four images when the user clicks the success button. let options: CaptureImageOption ...

Different JQuery countdowns in an iteration using Django

I'm in the process of developing a sports app using Django. One of the key features I want to include is the ability to display a list of upcoming matches with a countdown timer for each match. Currently, I have managed to implement a single countdow ...

Extracting key-value pairs and unkeyed values from a JSON string during deserialization

Here is a JSON string that I attempted to deserialize, containing key-value pairs and values without keys: {"build":42606,"torrentc": "928729876"} "torrents:[["3C50FB27DB1469EFFD2F7BEAB9997D6425416380",136,"Westworld.S01E02.720p.HDTV.x265.ShAaNiG.mkv",31 ...

The best method for quickly loading a webpage that is over 20MB in size

My website is a single-page calendar featuring a full year's worth of images. With 344 requests and a total load size of 20MB, the page consists of a simple PHP script without a database. The requests include a CSS file (15KB), 4 JS files (20KB), two ...

Guide on converting XML and JSON data in Swift 3

As a newcomer to IOS, I am looking to convert some mixed data (combination of XML and JSON) received from a SOAP web service into an array using Swift 3. This data is being received as a string variable in the parser method. func connection(_ connection: ...

What is the best way to update the value of a preact signal from a different component?

export const clicked = signal(false); const handleClickDay = (date) => { const day = date.getDate().toString().padStart(2,'0') const month = (date.getMonth()+1).toString().padStart(2,'0') const year = da ...

Struggling with a minor glitch in a straightforward coin toss program written in JavaScript

I'm a newcomer to JavaScript programming and I am struggling with understanding how the execution flow is managed. I attempted to integrate an animation from "Animation.css" into a coin toss program, but encountered an issue. When trying to use JavaSc ...

Ensure that certain attributes are present in a setup file for the Atom IDE using an Ansible playbook

As I embark on the journey of installing and setting up the Atom Editor IDE with Ansible, a question arises in my mind. While I can extract and analyze a JSON file using Ansible, I find myself at a crossroads when it comes to altering or adding fields with ...

Issue with 'backface-visibility' CSS3 property not functioning on any versions of Internet Explorer

I'm looking to implement a specific animation in Internet Explorer. The goal is to rotate an image like a coin, displaying a different image on the other side. I suspect that the issue lies with Backface-visibility in IE, but I'm not entirely sur ...