Javascript 在javascript中序列化和反序列化数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11312046/
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
Serializing and unserializing an array in javascript
提问by Lukmo
I'm using the tag-it library for jquery to make a tagging system (a bit like the stackoverflow one).
我正在使用 jquery 的 tag-it 库来制作标记系统(有点像 stackoverflow 的系统)。
After the user types his tags the library returns a javascript array that I want to save in a MySQL database. I didn't find a serialize and unserialize function in javascript.
在用户键入他的标签后,库返回一个我想保存在 MySQL 数据库中的 javascript 数组。我没有在 javascript 中找到序列化和反序列化函数。
Before coding my own function I'd like to make sure I'm not reinventing the wheel here. It seems crazy that there is no native way to save an array to a database and then use it again.
在编写我自己的函数之前,我想确保我没有在这里重新发明轮子。没有本地方法可以将数组保存到数据库然后再次使用它,这似乎很疯狂。
tl;dr => how can I save a javascript array in a MySQL database to reuse it later ?
tl;dr => 如何将 javascript 数组保存在 MySQL 数据库中以便以后重用?
回答by Sirko
You can use JSON.stringify()
(MDN docu) and JSON.parse()
(MDN docu) for converting a JavaScript object into a string representation to store it inside a database.
您可以使用JSON.stringify()
( MDN docu) 和JSON.parse()
( MDN docu) 将 JavaScript 对象转换为字符串表示形式以将其存储在数据库中。
var arr = [ 1, 2, 3 ];
var serializedArr = JSON.stringify( arr );
// "[1, 2, 3]"
var unpackArr = JSON.parse( serializedArr );
// identical array to arr
If your backend is written in PHP, there are similar methods to work with JSON strings there: json_encode()
(PHP docu) and json_decode()
(PHP docu).
如果你的后端是用PHP编写的,也有类似的方法来使用JSON字符串有工作:json_encode()
(PHP实况)和json_decode()
(PHP实况)。
Most other languages offer similar functionalities for JSON strings.
大多数其他语言为 JSON 字符串提供类似的功能。
回答by Engineer
You can use JavaScript Object Notation
(JSON
) format.
您可以使用JavaScript Object Notation
( JSON
) 格式。
Javascript
supports these methods:
Javascript
支持这些方法:
JSON.stringify-> serializes object to string
JSON.parse-> deserializes object from string
JSON.stringify->将对象序列化为字符串
JSON.parse->从字符串反序列化对象
回答by raina77ow
How about just JSONing it?
仅使用JSON怎么样?
var arr = [1,2,3];
var arrSerialized = JSON.stringify(arr);
...
var arrExtracted = JSON.parse(arrSerialized);
By the way, JSON is often used for serializing in some other languages, even though they have their own serializing functions. )
顺便说一句,JSON 通常用于在其他一些语言中进行序列化,即使它们有自己的序列化功能。)