将 document.cookie 等字符串转换为对象
我有一个类似于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
最短路线
The shortest way
为什么这里需要
JSON.parse
?修改数组示例Why exactly do you need
JSON.parse
in here? Modifying your arrays example注意: document.cookie(问题标题)以分号分隔,而不是逗号分隔(问题)...
使用
reduce
的替代方案:note : The document.cookie (question headline) is semicolon separated and not comma separated (question) ...
An alternative using
reduce
:使用
URLSearchParams
和对象.fromEntries
,避免循环和临时变量。解析
document.cookie
:针对问题范围(cookie之间用
、
分隔,存储在变量str
中)A way to parse cookies using native methods like
URLSearchParams
andObject.fromEntries
, avoiding loops and temporary variables.Parsing
document.cookie
:For the scope of the question (cookies are separated by
,
and stored in variablestr
)给定一个包含中间形式的数组
a
:然后简单地:
Given an array
a
containing your intermediate form:then simply:
解析cookies(IE9+):
parse cookies (IE9+):
要将其转换为对象,只需从头开始执行即可:
然后,如果您想要其中的 JSON:
To convert it to an object, just do that from the beginning:
Then, if you want JSON out of it:
我想到的第一件事是,我将其保留为原始版本,但 cookie 不应该为空,否则将会出现 json 解析错误
快速可靠的版本 - cookie 到对象
和获取单个 cookie 的短函数
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
fast and reliable version - cookie to object
and short function for get single cookie
这是相当糟糕的数据,只要它不使用 ,= 这就会对该数据起作用
That's pretty crappy data, as long as its not using ,= this would work on that data
我是 John Resig 的“搜索但不替换” 的粉丝此类事情的方法:
工作示例: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:
工作示例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:
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()
ormatch()
.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:
Working example 2: http://jsfiddle.net/cm6MT/1/
更新后的解决方案的替代版本,用于检查 null/空字符串并仅返回一个空对象,并且还允许使用自定义分隔符。
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.
上述大多数解决方案都会因 Google 设置的
__gads
cookie 而失败,因为它在 cookie 值中使用“=”字符。解决方案是使用正则表达式而不是调用
split('=')
: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('=')
:只需调用
getCookie()
,它就会返回当前网站的所有cookie。如果您有一个名为“mycookie”的 cookie,您可以运行
getCookie()['mycookie'];
,它将返回 cookie“mycookie”的值。还有一个 One-Line 选项:
可以使用与上述相同的方法使用此选项。
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:
This one can be used with the same methods as above.