Error encountered while trying to store a JSON object in local storage

When attempting to insert a JSON in localStorage, I am encountering the error

Unexpected token ~ in JSON at position 3
during the parse process.

Here is how I am inserting the data into localStorage:

localStorage.setItem(
    "users",
    `"[\"~#iM\",[\"loading\",false,\"auth\"]]"`
);

However, in localStorage, the data appears as:

"["~#iM",["loading",false,"auth"]]"

Attempting to parse it using:

JSON.parse("["~#iM",["loading",false,"auth"]]")

results in an error, while using:

JSON.parse("[\"~#iM\",[\"loading\",false,\"auth\"]]")

works correctly. The presence of \ is crucial. How can I maintain them in localStorage?

Answer №1

If my understanding is correct, you are interested in storing and retrieving objects from the localStorage. As you may already know, localStorage can only store strings.

The simplest way to accomplish this is to convert the object into a string using JSON.stringify:

const myKey = 'exampleKey';

function saveToLocalStorage(obj) {
localStorage.setItem(myKey, JSON.stringify(obj));
}

function retrieveFromLocalStorage() {
return JSON.parse(localStorage.getItem(myKey));
}


let sampleObjectToStore = [
  "~#iM",
  [
    "loading",
    false,
    "auth"
  ]
];

saveToLocalStorage(sampleObjectToStore);

let retrievedObject = retrieveFromLocalStorage();
console.log(retrievedObject)

PS: The revised example provided by you is not functioning properly due to double quoting. Simply remove the outer backticks to rectify the issue, like this:

  localStorage.setItem(
    "users",
    "[\"~#iM\",[\"loading\",false,\"auth\"]]"
  );

Answer №2

Remove any additional quotes or backticks around the outer []

  localStorage.setItem(
    "users",
    `[\"~#iM\",[\"loading\",false,\"auth\"]]`
  );

  console.log(JSON.parse(localStorage.getItem( "users")))

View the live demo here

Answer №3

  localStorage.setItem(
    "data",
    `["~#iM",["loading",false,"auth"]]`
  );

  console.log(JSON.parse(localStorage.getItem("data")))

I found success using this method, no need for the backward slashes.

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

Failure to achieve success with jQuery Ajax

success in my AJAX call is not triggering at all, leaving me puzzled as to why. None of the alerts specified in the AJAX file are appearing. The form: <form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg"> <label ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Showing a series of text entries one after the other, each appearing with a smooth fade-in and fade-out

I am eager to showcase a list of text in a sequential order, implementing a fade-in/fade-out effect and concluding with the display of an image. Additionally, I aim to have all the text centered on the page. <div>a<div> <div>b</div> ...

Kivy: Issue encountered on iOS while working with JSON file for High Score

I attempted to implement a highscore tracker for an application using a JSON file and the json storage language in Kivy. After importing JSONstore, I included the following code in my main game class: class Game(FloatLayout): highscorejson = JsonStor ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

Is there a way to display the product name in the input field when it is selected using the keyboard?

One of our team members has created an angular js script for autocomplete search functionality. Typing keywords in the search bar will return a list of candidates. However, when using arrow keys to navigate through the candidates, the product id is displ ...

Unpacking a collection in Xamarin using SQLite

I am currently facing an issue with storing a list in my Xamarin Forms App. I have successfully converted the JSON to C# using json2csharp for the ticket model. Additionally, I included the TextBlob to avoid getting an error message from SQLite stating tha ...

Display or Conceal Sub-Header according to Scrolling Position

Question: My goal is to create a specific animation on my website. When loading the page on mobile, I want to display the div with ID "sub-header", but once the user scrolls more than 50px down, I want to hide it. Additionally, if the user scrolls up by 60 ...

Develop a dynamic daily messaging system

I'm interested in incorporating a daily changing message feature on my website. My plan is to store all the messages in a MySQL database and have them displayed daily. Any guidance on how to achieve this would be highly appreciated! Thank you, I ha ...

jQuery providing incorrect measurements for an element's height

I am encountering an issue with obtaining the height of the #header element in my AngularJS application. Despite using jQuery, the returned height seems to be incorrect. The current code snippet looks like this: $(document).ready(function() { function ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Return empty parameters for nested routes efficiently

Here is an example of my situation: localhost:8000/api/news?category=tech At the moment, I have a router set up for the /api section and another one specifically for /api/news. However, when I attempt to display req.params in the /api/news router, it doe ...

Mapping JSON data to a HashMap

I pull data from a JSON file in the format: "B11, B12, B22, F11, F22, F1, F2, F3." After receiving this data, I have a layout with 50 icons. My goal is to make 8 icons VISIBLE and the remaining 42 icons INVISIBLE. I thought about using a HashMap for this ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

The Protractor actions().mouseMove function does not seem to function properly in Firefox and IE, although it works perfectly in Chrome

I've encountered an issue with the mouseMove command while using the actions class. The error occurs specifically when running the script on Firefox and IE, but works fine on Chrome. Below is the code snippet I attempted: browser.get("https://cherch ...

Utilizing NodeJS to Extract Data from MongoDB and Export to JSON File

I'm struggling to figure out how to write a specific field from my mongodb database to a json file using node js. Can anyone provide guidance or resources? I haven't had much luck finding helpful information so far. ...

What is the best way to conduct synchronous testing of animations in AngularJS version 1.3.15?

Encountering a migration issue with angular-animate.js while transitioning from version 1.2 to 1.3. Here is the animation code snippet: 'use strict'; angular.module('cookbook', ['ngAnimate']) .animation('.slide-down& ...

Using JQuery to search for and remove the id number that has been clicked from a specific value

I am in need of assistance with deleting the clicked id number from an input value using jQuery. I am unsure of how to proceed with this task and would appreciate some guidance. To simplify my request, let me explain what I am trying to accomplish. Take ...

Ways to update a component's state by clicking a button located on a different component

Seeking help with changing a parent state value when clicking a button. Although there are numerous similar queries out there, I'm really struggling to grasp the concept. I've attempted lifting the state up but haven't quite nailed it yet. ...

Implementing a JavaScript file and ensuring W3C compliance

I recently purchased a template that included a javascript file in the main page with the following code: <script src="thefile.js?v=v1.9.6&sv=v0.0.1"></script> Upon inspection, I noticed there are two arguments at the end of the file ...