convert python List to javascript array

Chris Rebert clp2 at rebertia.com
Fri Sep 2 19:26:15 CEST 2011


On Fri, Sep 2, 2011 at 8:34 AM, Vineet Deodhar <d_vineet at yahoo.com> wrote:
> Hi !
> Within a web framework, I want want to pass a python sequence (list or
> tuple) to client-side javascript function as an array (javascript
> compatible)
> e.g., I have this list:
> L = ['spam', 'ham', 'eggs', 12, (13.63)]
> What is the correct way to convert L to javascript array format?
> 1) jsonify the list and pass it to javascript
> (whether json format & javascript array are similar?)

JSON is in fact a subset of JavaScript, and modern browsers now
include a specific API for parsing and generating it
(https://developer.mozilla.org/En/Using_native_JSON ).
Python likewise has a JSON module in the std lib:
http://docs.python.org/library/json.html

> OR
> 2)
>>> import array
>>> y = array.array(i, L)
>  then return y to javascript function
> But the problem with this method is, it will give an array of basic values
> only.

The word "array" gets tossed around a lot by programmers. The `array`
module is not at all what you want in this case.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list