Learning
Learning

Reputation: 20031

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

Upvotes: 2

Views: 1607

Answers (3)

Joe Ireland
Joe Ireland

Reputation: 21

What about massaging the string into proper JSON, parsing it into a JSON Object, and using the fields from there?

It's less stable in that changes to the input string may break the function, but it is secure in that it's calling JSON.parse() rather than eval().

   function reformatCookieInput(inputString) {
    inputString = inputString.replace(/'/g, "");  //global strip out single quotes currently wrapping stamp
    inputString = inputString.replace(/,/g, `", "`); //global replace commas with wrapped commas
    inputString = inputString.replace(/:/g, `":"`); //same idea with colons
    inputString = inputString.replace("{", `{"`); //rewrap start of JSON string
    inputString = inputString.replace("}", `"}`); //rewrap end of JSON string

    return inputString;
}

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

const properJSONObject = JSON.parse(reformatCookieInput(input));
console.log(properJSONObject);

Upvotes: 1

vihtor
vihtor

Reputation: 275

Wrap this string by ( and ). Then parse like as display follow

Attention! But you need be ensure input string (which received from cookie) not contains bad code. Such as unknown injected function. In this case, the function will be executed on client browser, with access to private data (cookie, localStorage, data from html-forms).

const input = "{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}"
const object = eval("(" + input + ")");
alert(object.necessary);

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371118

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.

Upvotes: 3

Related Questions