3

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? :)

RadiantHex
  • 24,907
  • 47
  • 148
  • 244

2 Answers2

4

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));
david
  • 17,925
  • 4
  • 43
  • 57
  • @david: thanks for this! Any ideas on how I could reduce the length of the string? – RadiantHex Dec 22 '10 at 03:28
  • not really, you could try base64 encoding (I'll add it to the answer) but if you're passing truly huge lists you should probably be using a post. – david Dec 22 '10 at 03:32
  • Oh, ahaha you had the same idea > – david Dec 22 '10 at 03:33
  • @david: haha we posted at the same time! :) btw post would be good if I could get cross-domain POSTing working. One of the panes is that IE limits the length of URLs. – RadiantHex Dec 22 '10 at 03:38
  • The people here did some crazy stuff with iframes to get cross domain posts working: http://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via-javascript – david Dec 22 '10 at 03:43
  • @david This is the solution that I thought of. Also, POST is better for large strings. – qw3n Dec 22 '10 at 03:50
  • @david: found out that URLs max_length in real world is 2000 characters... I guess this is duable. – RadiantHex Dec 22 '10 at 03:54
2

jQuery.param() sounds good.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • hi thanks for the reply! :) Unfortunately the method vastly inflates data, I'm trying to be as compact as possible. – RadiantHex Dec 22 '10 at 03:26