I have a written a source program in python that calculates and returns a numpy array of 3 numbers. Now ,i am trying to pass this array to a javascript front end program to display. So far , i have tried using a child process in js invoking the python program, but i am stuck in the array transfer part. I have also looked at python-shell npm package , but have no idea how to work with it. How do i proceed? Is it better if i convert the array to a json file and send the json to the js program?
-
is the python program a web server? if so send the python array as a json to frontend javasctipt appmiqe– miqe2016-06-06 08:06:53 +00:00Commented Jun 6, 2016 at 8:06
-
1Convert the array to a list and then a JSON string.hpaulj– hpaulj2016-06-06 09:23:59 +00:00Commented Jun 6, 2016 at 9:23
Add a comment
|
2 Answers
Python has a module to encode objects as JSON strings:
import json
In [54]: json.dumps(np.arange(10).tolist())
Out[54]: '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
Arrays in Javascript are similar to Python lists. numpy arrays add level of complexity that you don't need, especially with only 3 numbers.
Comments
If you only have 3 numbers, then you might as well use JSON. But if you have 300,000 then you should consider transferring them as compressed binary (e.g. zlib).
For example, if you are using Flask then
s = pickle.dumps(data, protocol=3)
e = zlib.compress(s)
r = make_response(e)
setattr(r,"mimetype", "application/octet-stream")
Then on the javascript side you need to unpack what you get from Ajax with
const encoded_data = pako.inflate(binary_array)
const gxl = mpickle.loads(encoded_data.buffer)
Details are here: