Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript array to python list?

Tags:

python

I want to make google trasnlate script. I am making a request to translate.google.com and google return an array but the array contains undefined items.You can imagine response comes as string. I can remove commas if there is more than one consecutive with regex etc. but I am looking best solution :)

How can I convert this javascript array to python list?

["a","b",,,"e"]

My script : http://ideone.com/jhjZe

like image 566
Mesut Tasci Avatar asked Dec 01 '22 06:12

Mesut Tasci


1 Answers

JavaScript part - encoding

In Javascript you do:

var arr = ["a","b",,,"e"];
var json_string = JSON.stringify(arr);

then you somehow pass json_string (now equal to "["a","b",null,null,"e"]" string) from JavaScript to Python.

Python part - decoding

Then, on Python side do:

json_string = '["a","b",null,null,"e"]'  # passed from JavaScript

try:
    import simplejson as json
except (ImportError,):
    import json

result = json.loads(json_string)

As a result you get [u'a', u'b', None, None, u'e'] in Python.

More links

See below:

  • demo of JavaScript part,
  • Documentation on JSON.stringify() at Mozilla Developer Network,
  • demo of Python part,

Dependencies

The above solutions require:

  • JSON.stringify() in JavaScript, which is in all mobile browsers, Chrome, Firefox, Opera, Safari and in IE since version 8.0 (more detailed list of compatible browsers is here),
  • json Python library (the above code will use simplejson optionally, if available, but is not required), which comes in standard library,

So, in short there are no external dependencies.

like image 156
Tadeck Avatar answered Dec 06 '22 10:12

Tadeck