Json serialization of ulab np.array generate syntax error

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
zaord
Posts: 96
Joined: Fri Jan 31, 2020 3:56 pm

Json serialization of ulab np.array generate syntax error

Post by zaord » Thu Dec 30, 2021 6:23 pm

Hi here,

I have this sample of code :

Code: Select all

result = json.dumps(np.array(range(100),dtype=np.float)).encode('ascii')

print( result)

array = json.loads(str(result, 'ascii'))
print( array)
giving this error :

b'array([0.0, 1.0, 2.0, ..., 597.0, 598.0, 599.0], dtype=float32)'
Traceback (most recent call last):
File "<stdin>", line 20, in <module>
ValueError: syntax error in JSON

Any idea about how I could json to pass numpy array through a serial connection like this git : https://github.com/dhylands/json-ipc

v923z
Posts: 168
Joined: Mon Dec 28, 2015 6:19 pm

Re: Json serialization of ulab np.array generate syntax error

Post by v923z » Sat Jan 08, 2022 8:01 am

zaord wrote:
Thu Dec 30, 2021 6:23 pm
Hi here,

I have this sample of code :

Code: Select all

result = json.dumps(np.array(range(100),dtype=np.float)).encode('ascii')

print( result)

array = json.loads(str(result, 'ascii'))
print( array)
giving this error :

b'array([0.0, 1.0, 2.0, ..., 597.0, 598.0, 599.0], dtype=float32)'
Traceback (most recent call last):
File "<stdin>", line 20, in <module>
ValueError: syntax error in JSON

Any idea about how I could json to pass numpy array through a serial connection like this git : https://github.com/dhylands/json-ipc
I think the problem is caused by the ellipses. You have 100 elements, but only 6 are printed by default.

You have two options. One is to change how the printout behaves, so that all elements are printed: https://micropython-ulab.readthedocs.io ... -printouts

Or you can check out the https://github.com/v923z/micropython-ulab/tree/complex2 branch, which implements the

Code: Select all

.tolist()
array method. https://numpy.org/doc/stable/reference/ ... olist.html This branch will be merged into master in a matter of days.

zaord
Posts: 96
Joined: Fri Jan 31, 2020 3:56 pm

Re: Json serialization of ulab np.array generate syntax error

Post by zaord » Sat Jan 08, 2022 12:38 pm

I did not know but ujson can't handle arrays.

So,Yes i did that, and now i am using bytearray.
Damien Georges solved my problem here :https://github.com/micropython/micropyt ... 1006264156
You need to evaluate the returned data, like this (on the PC):

mes_expr = pyb.exec("print(Grab_Full_Mes(0))")
mes = eval(str(mes_expr, "ascii"))
print(len(mes))
You may also be having issues with flow control and/or a broken Windows USB serial driver. In that case you may need to break up the data into smaller chunks and send them separately.

Post Reply