简体   繁体   English

Javascript:将关联数组转换为字符串并将其转换回来的最佳方法是什么?

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

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? 将此关联数组转换为字符串的最佳方法是什么,然后反之亦然,如何将字符串转换为关联数组?

There is nothing better than JSON for 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" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM