Question

I know there are several questions and answers about this, but I can't be really sure any of those will help me.

So this is my case, I'm using sympy library and a very few numpy functions too. I invoke these from node.js thinking about some web app, so I expect to receive any results in a json format.

I face two main problems here:

  1. Not whole sympy stuffs happen to be plain floats or even strings.
  2. After solving JSON encoding issues, will it be possible to generate JavaScript equivalent floating point numbers for a very simple managing?

More in detail I'm working right now with a Taylor sum series program (already coded) and about this line results, corresponding to numpy function:

puntosX = linspace(a,b,num=puntos).round(3)

I can't turn it to a JSON list, a print of puntosX will output:

[-10. -7.778 -5.556 -3.333 -1.111 1.111 3.333 5.556 7.778 10. ]

also

When I generate an array of expressions by this line:

sumterms.append( (fx.diff(w,i)/factorial(i)) * (x)**i )

Happens same being sumters in this case:

[x**3 - x - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

So, in a very simple black box approch this would mean, get all elements from first list to be floats and all from second list to be strings. I think any lambda like line would help.

But, is there any way to tell this to json or demjson packages?

Was it helpful?

Solution

Converting your numpy array to a list works (if there is a version of json that handles arrays directly it probably is doing this conversion). Here I'm working with a sample 2d array.

In [8]: x=np.linspace(0,1,10).reshape(2,5).round(3)

In [9]: x
Out[9]: 
array([[ 0.   ,  0.111,  0.222,  0.333,  0.444],
       [ 0.556,  0.667,  0.778,  0.889,  1.   ]])

In [10]: json.dumps(x.tolist())
Out[10]: '[[0.0, 0.111, 0.222, 0.333, 0.444], [0.556, 0.667, 0.778, 0.889, 1.0]]'

What kind of output do you want transfer from sympy? If the formulas are turned into strings, json.dumps should have no problems.

OTHER TIPS

I think you could use the Python built-in json package and the dumps function When all you need is convert your lists to JSON format it's as simple as:

>>> puntosX
[-10.0, -7.778, -5.556, -3.333, -1.111, 1.111, 3.333, 5.556, 7.778, 10.0]
>>> import json
>>> json.dumps(puntosX)
'[-10.0, -7.778, -5.556, -3.333, -1.111, 1.111, 3.333, 5.556, 7.778, 10.0]'

You can wrap it in a "puntos" object like this:

>>> json.dumps({'puntos': puntosX})
'{"puntos": [-10.0, -7.778, -5.556, -3.333, -1.111, 1.111, 3.333, 5.556, 7.778, 10.0]}'

And when you want the puntos to be list of string values, I would suggest to do it like this:

>>> json.dumps({'puntos': [str(p) for p in puntosX]})
'{"puntos": ["-10.0", "-7.778", "-5.556", "-3.333", "-1.111", "1.111", "3.333", "5.556", "7.778", "10.0"]}'

I hope it is what you wanted to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top