Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example:

function onExit(){
   localStorage.setItem("my_object","'" + JSON.stringify(object) + "'");
 }

When retrieving this data from localStorage, it may look like this:

'{"date":"2016-05-31T23:00:00.000Z","Name":"name","Code":"code","required":"false"}'

Interestingly, calling JSON.parse directly on the object works fine:

JSON.parse('{"date":"2016-05-31T23:00:00.000Z","Name":"name","Code":"code","required":"false"}')

However, trying to parse the object stored in localStorage throws an error:

JSON.parse(localStorage.my_object)

This results in an 'unexpected character at line 1 of JSON data' message. The issue could be related to how the object is being stored or retrieved. It may be worth exploring different methods to resolve this problem.

Answer №1

To save your object without quotes, follow this example:

function onSave(){
   localStorage.setItem("object",JSON.stringify(obj));
 }

Alternatively, if you saved the object with quotes, make sure to remove them before parsing the object.

Answer №2

Using extra quotes ("'") when wrapping JSON.stringify(object) is unnecessary because it already returns a usable string.

localStorage.setItem("my_object",JSON.stringify(object));

If you want to retrieve and decode the JSON object, simply call getItem

JSON.parse(localStorage.getItem("my_object"))

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

The function buf.writeBigUInt64BE is not recognized as a valid function and returns an undefined error

I'm attempting to implement the code below on my React Native iOS device: import { Buffer } from "buffer"; const buf = Buffer.alloc(8) buf.writeBigUInt64BE(BigInt(123), 0) const value = buf.readBigUInt64BE(0) console.log(value) However, I&a ...

What is the process for transforming XML into JSON with C# and LINQ?

Trying to convert an XML file into JSON on the server but facing a challenge due to different value types in each column. Any suggestions or examples of similar implementations using C#/LINQ would be really helpful as I am new to working with XML. The goa ...

Using CSS or JavaScript to trigger events while scrolling with touch

Imagine a scenario where multiple boxes are stacked on top of each other: <div style="width: 100%; height: 100px; background-color: red"> stuff </div> By clicking or touching them, the background color can be easily changed using CSS (:hover, ...

Traversing a JSON array using Shell scripting techniques

Within my data.json file, I have JSON data structured like this: [ {"original_name":"pdf_convert","changed_name":"pdf_convert_1"}, {"original_name":"video_encode","changed_name":"video_encode_1"}, {"original_name":"video_transcode","changed_name":"v ...

"UIWebView experiences a crash when a long press gesture is performed on a textarea element

Looking to implement a custom keyboard for UIWebView that is entirely based on HTML/JS/CSS for compatibility across multiple devices. To achieve this, I included a notification as shown below: [[NSNotificationCenter defaultCenter] addObserver:self selecto ...

Having trouble with Route Param in React after deploying the application to an Apache server

I am facing an issue with my React app that uses react-router. I have included router params in my Routes, and while it works fine locally, the link with route params is not working once deployed on an Apache server. Can someone assist me in resolving this ...

An unexpected character was found during the parsing of the value: S. Path '', line 0, position 0

Despite the abundance of posts on this topic, I struggled to find a solution that addressed my specific issue. I want to clarify that I have already verified that the encoding is correct. Additionally, the Exception sometimes occurs and sometimes doesn&apo ...

Vue component fails to render due to a simple issue

I've been diving into Vue.JS and I'm facing an issue where the component I created isn't showing up on the page. Here's a snippet of my component: import Vue from 'vue' const card = new Vue({ el: '#card', data: ...

Personalize buttons using SweetAlerts 2 customization options

In order to adhere to the custom design provided to me, I am currently using SweetAlerts 2 for all dialog boxes that require confirmation or cancellation. Specifically, I require the cancel button to have a white background with teal text and a teal border ...

Ways to extract the initial layer of information from a JSON document

I have a JSON file named movie.json stored externally, and it follows this format: { "action": [ { "id": "1001", "name": "Matrix" }, { "id": "1002", & ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

Tips for sorting ng-Table using an array of numerous values

I am currently working on implementing angular-selectize.js (https://github.com/machineboy2045/angular-selectize) into my project. This will create a search box that allows for entering multiple values to filter all cells in an ng-Table without the need to ...

Differences between ES6 class static method and regular function

When working with NodeJS, I am planning to create some utility functions. I have two options in mind. The first option involves using the traditional approach: module.exports = { random: () => Math.random(), }; Alternatively, I could use an ES6 c ...

Storing data in localStorage and serializing it using JSON.stringify and

Currently, I am developing a project that enables users to share memories of places they have visited and also tracks the location and time when the memory was recorded. One hurdle I'm facing involves incorporating localStorage into the application. I ...

Leverage JsonConvert for Serializing Objects with different arguments

Hi there! I am working on a project where I need to return Json data to Ajax in order to update some HTML on my page. The C# code I'm using looks like this: public JsonResult AddToCart(int id, int sizeid, int sizeVal, int catID) { Cake C = db.Cak ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

Passing a variable between pages in PHP: a simple guide

In my *book_order* page, I allow users to input orders into a table called *order_management*. The order_id is auto-incremented in this table. After submitting the page, I need to pass the order_id to another page named *book_order2* where products can be ...

How can I change the color of a cube in Three.js?

I'm currently working on developing a basic 3D game using three.js. My goal is to create colored cubes, but I'm encountering an issue where all the cubes are displaying the same color. My cube creation code looks like this: var geometry = new ...

Is it better to Vuex - manipulate store item twice, trigger new items, or perform transformations within components each time they are mounted?

I am considering performing two separate transformations on a single, large store item and then saving the results as two new store items. For instance: setEventsData: (state, data) => {...} // main huge master object // perform transformations on it an ...

What steps can be taken to address an unusual conflict arising between a form post and an ajax post

One web page features the use of ajax for editing existing values. This is achieved by utilizing jQuery Inline Edit to post new data, update records, and return with success. The process works well initially. Subsequently, I implemented the functionality ...