No, you don't have to. And, yes, you can do just that! You can pass it as one string like you did, and then get it and evaluate it in Python.
You can use:
evaldict = {}
array = eval("[[1, 2, 3], [4, 5, 6]]", evaldict)
Although I forced the scope of evaluation to be encapsulated in a dict, THIS IS NOT SECURE!
Because someone can pass some other Python expression to be evaluated. Therefore better use literal_eval() from ast module which doesn't evaluate expressions.
I suggest you tu use jquery and its post() method to do this, use a POST HTTP method instead of GET.
Also, this could be nice and securely done using json (send the json instead of just stringifying JS array manually.
And using it to avoid evaluating a list directly (in Python).
Here is the client side using jquery:
<html><head><title>TEST</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
pyurl = "http://example.com/cgi-bin/so.py";
function callpy (argdict) {
$.post(pyurl, argdict, function (data) {
// Here comes whatever you'll do with the Python's output.
// For example:
document.getElementById("blah").innerHTML = data;
}, "text");
};
var myArray = [["one", "two"], ["foo", "bar"]];
// This is array shape dependent:
function stringify (a) {
return "['" + a.join("', '") + "']";
};
myArrayStr = "[";
for (x = 0; x<myArray.length; x++) {
myArrayStr += stringify(myArray[x]) +", ";
}
myArrayStr += "]";
// This would be better, but it is library dependent:
//myArrayStr = JSON.stringify(myArray);
</script>
</head><body>
<a href="#" onclick="javascript:callpy({'array': myArrayStr});">Click me!</a>
<p id="blah">
Something will appear here!
</p>
</body></html>
And this is the server-side CGI:
#! /usr/bin/env python
try:
# This version of eval() ensures only datatypes are evaluated
# and no expressions. Safe version of eval() although slower. It is available in Python 2.6 and later
from ast import literal_eval as eval
except ImportError:
import sys
print "Content-Type: text/html\n"
print "<h1>literal_eval() not available!</h1>"
sys.exit()
import cgi, cgitb
import sys
cgitb.enable()
print "Content-Type: text/html\n"
i = cgi.FieldStorage()
q = i["array"].value.strip()
print "I received:<br>"
print q
# Put here something to eliminate eventual malicious code from q
# Check whether we received a list:
if not q.startswith("[") and not q.endswith("]"):
print "Wrong query!"
sys.exit()
try: myArray = eval(q)
except: print "Wrong query!"; sys.exit()
if not isinstance(myArray, list):
print "Wrong query!"
sys.exit()
print "<br>Evaluated as:<br>"
print myArray
Now, note that using json on both sides would be faster and more flexible.