javascriptjqueryjquery-cookie

Read value from string which looks like jSon format


I have cookie value stored in following format

{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}

and i need to read following values of

necessary
preferences
statistics
marketing

Not sure how to to read values correctly, i tried following code assuming it is jSON format

        Cookies.get('CookieConsent')

        //Parse the cookie to Object

        cookieval = Cookies.get('CookieConsent');
        console.log(cookieval);

        console.log("Necessary: " + Boolean(cookieval.necessary));
        console.log("Prefrences: " + Boolean(cookieval.preferences));
        console.log("Statistics: " + Boolean(cookieval.statistics));
        console.log("Marketing: " + Boolean(cookieval.marketing));

But this code always returns false.

I use following Jquery to read Cookie values https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js


Solution

  • You do not have JSON format - you have something closer to JS object literal notation, except that it's a string rather than JS code, so can't use JSON.parse unfortunately.

    If the values don't have commas or colons, you can split the string by commas and reduce into an object:

    const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
    const obj = input
      .slice(1, input.length - 1)
      .split(',')
      .reduce((obj, str) => {
        const [key, val] = str.split(':');
        obj[key] = val;
        return obj;
      }, {});
    console.log(obj);

    eval is another option, but that's unsafe.