2

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?

2
  • is the python program a web server? if so send the python array as a json to frontend javasctipt app Commented Jun 6, 2016 at 8:06
  • 1
    Convert the array to a list and then a JSON string. Commented Jun 6, 2016 at 9:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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:

Is there an already published Javascript solution to traverse Python pickled objects without using Node.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.