我有以下格式存储的cookie值



我需要阅读以下值

necessary
preferences
statistics
marketing

不知道如何正确读取值,我尝试使用以下代码(假设它是jSON格式)
        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));

但是此代码始终返回false。

我使用以下Jquery读取Cookie值https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js

最佳答案

您没有JSON格式-除了它是一个字符串而不是JS代码之外,您更接近JS对象文字符号,因此很遗憾不能使用JSON.parse

如果值没有逗号或冒号,则可以通过逗号对字符串进行split编码,然后将reduce编码为对象:

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是另一种选择,但这是不安全的。

09-26 22:34
查看更多