将 document.cookie 等字符串转换为对象

发布于 2024-10-18 06:32:56 字数 972 浏览 2 评论 0原文

我有一个类似于 document.cookie 的字符串:

var str = 'foo=bar, baz=quux';

将其转换为数组非常简单:

str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    str[i].split('=');
}

它会生成如下内容:

[['foo', 'bar'], ['baz', 'quux']]

转换为对象(在这种情况下更合适)更困难。

str = JSON.parse('{' + str.replace('=', ':') + '}');

这会产生一个像这样的对象,这是无效的:

{foo: bar, baz: quux}

我想要一个像这样的对象:

{'foo': 'bar', 'baz': 'quux'}

注意:我在示例中使用了单引号,但是在发布代码时,如果您使用 JSON.parse(),请记住它需要双引号而不是单引号。


更新

谢谢大家。这是我将使用的函数(供将来参考):

function str_obj(str) {
    str = str.split(', ');
    var result = {};
    for (var i = 0; i < str.length; i++) {
        var cur = str[i].split('=');
        result[cur[0]] = cur[1];
    }
    return result;
}

I have a string similiar to document.cookie:

var str = 'foo=bar, baz=quux';

Converting it into an array is very easy:

str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    str[i].split('=');
}

It produces something like this:

[['foo', 'bar'], ['baz', 'quux']]

Converting to an object (which would be more appropriate in this case) is harder.

str = JSON.parse('{' + str.replace('=', ':') + '}');

This produces an object like this, which is invalid:

{foo: bar, baz: quux}

I want an object like this:

{'foo': 'bar', 'baz': 'quux'}

Note: I've used single quotes in my examples, but when posting your code, if you're using JSON.parse(), keep in your mind that it requires double quotes instead of single.


Update

Thanks for everybody. Here's the function I'll use (for future reference):

function str_obj(str) {
    str = str.split(', ');
    var result = {};
    for (var i = 0; i < str.length; i++) {
        var cur = str[i].split('=');
        result[cur[0]] = cur[1];
    }
    return result;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

孤城病女 2024-10-25 06:32:56

最短路线

 document.cookie.split('; ').reduce((prev, current) => {
    const [name, ...value] = current.split('=');
    prev[name] = value.join('=');
    return prev;
  }, {});

The shortest way

 document.cookie.split('; ').reduce((prev, current) => {
    const [name, ...value] = current.split('=');
    prev[name] = value.join('=');
    return prev;
  }, {});
不再见 2024-10-25 06:32:56

为什么这里需要 JSON.parse ?修改数组示例

let str = "foo=bar; baz=quux";

str = str.split('; ');
const result = {};
for (let i in str) {
    const cur = str[i].split('=');
    result[cur[0]] = cur[1];
}


console.log(result);

Why exactly do you need JSON.parse in here? Modifying your arrays example

let str = "foo=bar; baz=quux";

str = str.split('; ');
const result = {};
for (let i in str) {
    const cur = str[i].split('=');
    result[cur[0]] = cur[1];
}


console.log(result);

夏夜暖风 2024-10-25 06:32:56

注意: document.cookie(问题标题)以分号分隔,而不是逗号分隔(问题)...

使用 reduce 的替代方案:

var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
  var arr = pairStr.split('=');
  if (arr.length === 2) { result[arr[0]] = arr[1]; }
  return result;
}, {});

note : The document.cookie (question headline) is semicolon separated and not comma separated (question) ...

An alternative using reduce :

var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
  var arr = pairStr.split('=');
  if (arr.length === 2) { result[arr[0]] = arr[1]; }
  return result;
}, {});
隐诗 2024-10-25 06:32:56

使用 URLSearchParams对象.fromEntries,避免循环和临时变量。

解析document.cookie

Object.fromEntries(new URLSearchParams(document.cookie.replace(/; /g, "&")))

针对问题范围(cookie之间用分隔,存储在变量str中)

Object.fromEntries(new URLSearchParams(str.replace(/, /g, "&")))

A way to parse cookies using native methods like URLSearchParams and Object.fromEntries, avoiding loops and temporary variables.

Parsing document.cookie:

Object.fromEntries(new URLSearchParams(document.cookie.replace(/; /g, "&")))

For the scope of the question (cookies are separated by , and stored in variable str)

Object.fromEntries(new URLSearchParams(str.replace(/, /g, "&")))
柳絮泡泡 2024-10-25 06:32:56

给定一个包含中间形式的数组 a

[['foo', 'bar'], ['baz', 'quux']]

然后简单地:

var obj = {};
for (var i = 0; i < a.length; ++i) {
   var tmp = a[i];
   obj[tmp[0]] = tmp[1];
}

Given an array a containing your intermediate form:

[['foo', 'bar'], ['baz', 'quux']]

then simply:

var obj = {};
for (var i = 0; i < a.length; ++i) {
   var tmp = a[i];
   obj[tmp[0]] = tmp[1];
}
梦一生花开无言 2024-10-25 06:32:56

解析cookies(IE9+):

document.cookie.split('; ').reduce((result, v) => {
  const k = v.split('=');
  result[k[0]] = k[1];
  return result;
}, {})

parse cookies (IE9+):

document.cookie.split('; ').reduce((result, v) => {
  const k = v.split('=');
  result[k[0]] = k[1];
  return result;
}, {})
嘴硬脾气大 2024-10-25 06:32:56

要将其转换为对象,只需从头开始执行即可:

var obj = {};
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    var tmp = str[i].split('=');
    obj[tmp[0]] = tmp[1];
}

然后,如果您想要其中的 JSON:

var jsonString = JSON.stringify(obj);

To convert it to an object, just do that from the beginning:

var obj = {};
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    var tmp = str[i].split('=');
    obj[tmp[0]] = tmp[1];
}

Then, if you want JSON out of it:

var jsonString = JSON.stringify(obj);
微凉徒眸意 2024-10-25 06:32:56

我想到的第一件事是,我将其保留为原始版本,但 cookie 不应该为空,否则将会出现 json 解析错误

JSON.parse(`{"${document.cookie.replace(/=/g,'":"').replace(/; /g,'","')}"}`)

快速可靠的版本 - cookie 到对象

let c=document.cookie.split('; '),i=c.length,o={};
while(i--){let a=c[i].split('=');o[a[0]]=a[1]}

和获取单个 cookie 的短函数

getCookie=e=>(e=document.cookie.match(e+'=([^;]+)'),e&&e[1])

first thing that occurred to me, I'll leave it as the original version, but cookies should not be empty otherwise there will be a json parse error

JSON.parse(`{"${document.cookie.replace(/=/g,'":"').replace(/; /g,'","')}"}`)

fast and reliable version - cookie to object

let c=document.cookie.split('; '),i=c.length,o={};
while(i--){let a=c[i].split('=');o[a[0]]=a[1]}

and short function for get single cookie

getCookie=e=>(e=document.cookie.match(e+'=([^;]+)'),e&&e[1])
岛歌少女 2024-10-25 06:32:56

这是相当糟糕的数据,只要它不使用 ,= 这就会对该数据起作用

var text = 'foo=bar, baz=quux',
    pattern = new RegExp(/\b([^=,]+)=([^=,]+)\b/g),
    obj = {};

while (match = pattern.exec(text)) obj[match[1]] = match[2];

console.dir(obj);

That's pretty crappy data, as long as its not using ,= this would work on that data

var text = 'foo=bar, baz=quux',
    pattern = new RegExp(/\b([^=,]+)=([^=,]+)\b/g),
    obj = {};

while (match = pattern.exec(text)) obj[match[1]] = match[2];

console.dir(obj);
影子的影子 2024-10-25 06:32:56

我是 John Resig 的“搜索但不替换” 的粉丝此类事情的方法:

var str = 'foo=bar, baz=quux',
    arr = [],
    res = '{';

str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) { 
    arr.push('"' + key + '":"' + value + '"');
});

res += arr.join(",") + "}";

alert(res);

工作示例:http://jsfiddle.net/cm6MT/

使事情变得更加简单,无需 JSON 支持。当然,将相同的正则表达式与 exec()match() 一起使用也同样容易。


Whoops, I thought you wanted to convert to a JSON string, not an object. In that case, you only need to modify the code slightly:

var str = 'foo=bar, baz=quux',
    res = {};

str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) { 
    res[key] = value;
});
console.log(res.foo);
//-> "bar"

工作示例2:http://jsfiddle.net/cm6MT/1/

I'm a fan of John Resig's "Search and don't replace" method for this sort of thing:

var str = 'foo=bar, baz=quux',
    arr = [],
    res = '{';

str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) { 
    arr.push('"' + key + '":"' + value + '"');
});

res += arr.join(",") + "}";

alert(res);

Working example: http://jsfiddle.net/cm6MT/.

Makes things a lot simpler without the need for JSON support. Of course, it's just as easy to use the same regular expression with exec() or match().


Whoops, I thought you wanted to convert to a JSON string, not an object. In that case, you only need to modify the code slightly:

var str = 'foo=bar, baz=quux',
    res = {};

str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) { 
    res[key] = value;
});
console.log(res.foo);
//-> "bar"

Working example 2: http://jsfiddle.net/cm6MT/1/

葬花如无物 2024-10-25 06:32:56

更新后的解决方案的替代版本,用于检查 null/空字符串并仅返回一个空对象,并且还允许使用自定义分隔符。

function stringToObject(str, delimiter) {
    var result = {};
    if (str && str.length > 0) {
        str = str.split(delimiter || ',');
        for (var i = 0; i < str.length; i++) {
            var cur = str[i].split('=');
            result[cur[0]] = cur[1];
        }
    }
    return result;
}

An alternate version of your updated solution that checks for the null/empty string and just returns an empty object and also allows for custom delimiters.

function stringToObject(str, delimiter) {
    var result = {};
    if (str && str.length > 0) {
        str = str.split(delimiter || ',');
        for (var i = 0; i < str.length; i++) {
            var cur = str[i].split('=');
            result[cur[0]] = cur[1];
        }
    }
    return result;
}
べ映画 2024-10-25 06:32:56

上述大多数解决方案都会因 Google 设置的 __gads cookie 而失败,因为它在 cookie 值中使用“=”字符。

解决方案是使用正则表达式而不是调用 split('=')

document.cookie.split(';').reduce((prev, current) => {
  const [name, value] = current.split(/\s?(.*?)=(.*)/).splice(1, 2);
  prev[name] = value;
  return prev;
}, {});

Most of the above solutions fail with the __gads cookie that Google sets because it uses a '=' character in the cookie value.

The solution is to use a regular expression instead of calling split('='):

document.cookie.split(';').reduce((prev, current) => {
  const [name, value] = current.split(/\s?(.*?)=(.*)/).splice(1, 2);
  prev[name] = value;
  return prev;
}, {});
指尖上的星空 2024-10-25 06:32:56
function getCookie(){
   var o=document.cookie.split("; ");
   var r=[{}];
   for(var i=0;i<o.length;i++){
      r[o[i].split("=")[0]] = o[i].split("=")[1];
   }
   return r;
}

只需调用getCookie(),它就会返回当前网站的所有cookie。
如果您有一个名为“mycookie”的 cookie,您可以运行 getCookie()['mycookie'];,它将返回 cookie“mycookie”的值。
还有一个 One-Line 选项:

function getCookie(){var o=document.cookie.split("; ");var r=[{}];for(var i=0;i<o.length;i++){r[o[i].split("=")[0]] = o[i].split("=")[1];}return r;}

可以使用与上述相同的方法使用此选项。

function getCookie(){
   var o=document.cookie.split("; ");
   var r=[{}];
   for(var i=0;i<o.length;i++){
      r[o[i].split("=")[0]] = o[i].split("=")[1];
   }
   return r;
}

Just call getCookie() and it will return all cookies from the current website.
If you have a cookie called 'mycookie' you can run getCookie()['mycookie']; and it will return the value of the cookie 'mycookie'.
There is also a One-Line option:

function getCookie(){var o=document.cookie.split("; ");var r=[{}];for(var i=0;i<o.length;i++){r[o[i].split("=")[0]] = o[i].split("=")[1];}return r;}

This one can be used with the same methods as above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文