Javascript:将关联数组转换为字符串并稍后以其他方式返回的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14430859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:44:14  来源:igfitidea点击:

Javascript: Best way to convert associative array to string and back the other way later?

javascriptarraysassociative-array

提问by Mark

I have an associative array as follows:

我有一个关联数组,如下所示:

var AssocArray = { id:0, folder:'Next', text:'Apple' };

Now I need to store this in a database, so I figure I would just convert this into a string, store it in the database and then pull it out of the database and put it back into a javascript array later on.

现在我需要将它存储在一个数据库中,所以我想我只是将它转换为一个字符串,将它存储在数据库中,然后将它从数据库中拉出来,稍后再把它放回一个 javascript 数组中。

The catch is that the actual # of items, and the array variables will be different every time (hence why I wanted to store it as one long string instead).

问题是实际的项目数量和数组变量每次都会不同(因此我想将它存储为一个长字符串)。

What's the best way to convert this associative array into a string, and then also vice versa, how to convert a string into an associative array?

将此关联数组转换为字符串的最佳方法是什么,反之亦然,如何将字符串转换为关联数组?

回答by VisioN

There is nothing better than JSONfor it:

没有什么比JSON更好的了:

var str = JSON.stringify(obj);
// >> "{"id":0,"folder":"Next","text":"Apple"}"

var obj = JSON.parse(str);
// >> Object({ id: 0, folder: "Next", text: "Apple" })