Home > other >  JSON.stringify is distorting code adding \ inside strings?
JSON.stringify is distorting code adding \ inside strings?

Time:02-08

I am trying to save local storage info but what happens is I am getting \ added to all the items that are strings I mean as some answers stated it is caused by double stringfy ? issue is my blob action that saves the local storage refuse to handle the it unless is it is stringifed, long story short could this double stringfy needed for the function cause issues later, I have no problem when parsing back but the look of the saved elements looks really weird ?

//const ls = JSON.stringify(localStorage);
// "id":"\"159e17e9-19b7-453d-8e10-a411c7424586\"
// "groups":"{\"bee7bdc4-d888-46e6-93d7-ed0c\" : :[{\"id\":\"0e6e6426-4d79-4eea-9180-06111dd2a0e3\"}]
  
  
  
const config = {a: 'fdfgdg', b: 2}
console.log(JSON.stringify(config))

CodePudding user response:

When saving to localStorage use JSON.stringify (since Storage accepts only String values):

const myData = {some: "data", other: "stuff"};
localStorage.appData = JSON.stringify(myData);

When reading from localStorage, use JSON.parse:

const myData = JSON.parse(localStorage.appData || "{}");
console.log(myData);  // {some: "data", other: "stuff"}

Don't be afraid of escaped double-quotes with backslash! Otherwise it would end up in an invalid String format

const test = "this is \"something\""; // properly escaped quotes

Get used to see in console (on in LocalStorage) the escaped strings used for Keys os String properties of a JSON stringified Object literal:

"{\"prop\": \"some value\"}"   // Valid stringified JSON

perfectly fine.

Learn more about the JSON format.
JSON, in order to be valid, its keys need to be enclosed in double quotes. JSON.stringify will take care of adding quotes to a JS Object Literal keys for you.

CodePudding user response:

When you are getting a stringfied object and you want him to become an object again, there is another command to do so

JSON.parse(obj)

var obj = {
    id: '159e17e9-19b7-453d-8e10-a411c7424586',
    groups: '000e17e9-19b7-453d-8e10-a411c7424500'
}

var stringfiedObject = JSON.stringify(obj)
console.log(stringfiedObject)

var objectFromStringfiedObject = JSON.parse(stringfiedObject)
console.log(objectFromStringfiedObject)

CodePudding user response:

There's no "extra backslash", it's just your means of output show that extra backslash, because it is the way it renders string values (you probably use browser console for that, didn't you?).

Be sure, the actual stringified value does not contain any characters that are not supposed to be there.

  •  Tags:  
  • Related