在javascript中序列化和反序列化数组 [英] Serializing and unserializing an array in javascript
问题描述
我正在使用tag-it库来创建一个标记系统(有点像stackoverflow)。
I'm using the tag-it library for jquery to make a tagging system (a bit like the stackoverflow one).
用户输入标签之后library返回一个我想要保存在MySQL数据库中的javascript数组。我没有在javascript中找到序列化和反序列化函数。
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.
在编写我自己的函数之前,我想确保我不是在这里重新发明轮子。似乎很疯狂,没有本地方法将数组保存到数据库然后再次使用它。
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 =>如何保存javascript数组一个MySQL数据库以便以后重用它?
tl;dr => how can I save a javascript array in a MySQL database to reuse it later ?
推荐答案
你可以使用 JSON.stringify()
( MDN文档)和 JSON.parse用于转换JavaScript对象的()
( MDN文档)到字符串表示形式,将其存储在数据库中。
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.
var arr = [ 1, 2, 3 ];
var serializedArr = JSON.stringify( arr );
// "[1, 2, 3]"
var unpackArr = JSON.parse( serializedArr );
// identical array to arr
如果你的后端用PHP编写,有类似的在那里使用JSON字符串的方法: json_encode()
( PHP文档)和 json_decode()
( PHP文档)。
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).
大多数其他语言为JSON字符串提供类似的功能。
Most other languages offer similar functionalities for JSON strings.
这篇关于在javascript中序列化和反序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!