Home > Software engineering >  JSON stringify - parsing of json stringify object
JSON stringify - parsing of json stringify object

Time:06-09

I am trying to store an object on localstorage. And because localstorage only uses key: value, my object has to be .stringify().

How do I revert that stringified value back to an object?

linkedin_pixel_data= {
 50:{
   insight_tags:[
     {
      partnerId:2742940,
      status:Success
     }],
   pixels:[]
 };
const jsonObj = JSON.stringify(linkedin_pixel_data);

get from localstorage Output:

"{\"50\":{\"insight_tags\":[{\"partnerId\":\"2742940\",\"status\":\"Success\"}],\"pixels\":[]}}"

How to I parse this so that it will be in the original nested object form?

Any help guys?

CodePudding user response:

You can use JSON.parse(string) to get the object back.

const objToStr = JSON.stringify(object);  // serialize object to string
const strToObj = JSON.parse(objToStr);   // get object back

CodePudding user response:

Check out the code below and the results. There were a few minor errors in your code.

const linkedin_pixel_data = {
 50:{
   insight_tags:[
     {
      partnerId: 2742940,
      status: "Success"
     }],
   pixels:[]
 }
 };
const jsonString = JSON.stringify(linkedin_pixel_data);
console.log(jsonString);
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj[50].insight_tags[0].partnerId);
  • Related