RadiantHex
RadiantHex

Reputation: 25577

Good way to serialize a list? - Javascript/AJAX

just felt like asking this as there are always jewels popping up on stackoverflow :)

What I have is the following list:

list1 = [['command','arg1','arg2'], ['command2','arg1'], ... ]

How would you recommend to transform it into a string in order to be passed as ONE GET argument?

e.g.

http://webgame_site.com/command_list/?data=...

What I am currently doing is separating lists using commas , ; , but I don't like this idea as the method would break if I decide to introduce these within strings.

I'm trying to be as compact as possible.


One idea I've had is to encode the list into base64:

[['command','arg1','arg2'], ['command2','arg1']]
=> "W1snY29tbWFuZCcsJ2FyZzEnLCdhcmcyJ10sWydjb21tYW5kMicsJ2FyZzEnXV0="

which is shorter than URIencode


Any ideas? :)

Upvotes: 3

Views: 4630

Answers (2)

david
david

Reputation: 18288

Convert it to json then encode the characters using encodeURI.

var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = encodeURI(JSON.stringify(list1));

alert(encoded);

Edit for base64:

var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = btoa(JSON.stringify(list1));

alert(encoded);
alert(atob(encoded));

Upvotes: 4

Dr.Molle
Dr.Molle

Reputation: 117354

jQuery.param() sounds good.

Upvotes: 2

Related Questions