Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode function to JSON

I have an array with an element from the operator module. I tried storing this with JSON but but got the following error msg.

import operator as op
import json
array = [1,op.ge]
json_encoded = json.dumps(array)
f = open("test.json","w")
f.write(json_encoded)
f.close()

TypeError: <built-in function ge> is not JSON serializable

is there a workaround or another way to store this?

like image 252
Ahdee Avatar asked Feb 01 '26 00:02

Ahdee


1 Answers

You could use the pickle module, which can serialize objects, too:

import pickle
...
pickle_encoded = pickle.dumps(array)
...

Pickle will write a byte-stream, which won't be human-readable in contrast to JSON.

like image 158
miku Avatar answered Feb 02 '26 17:02

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!