I need to convert an image (can be any type jpg, png etc.) to JSON serializable.
I looked into the solution here but the accepted solution has a typo and I am not sure how to resolve it.
An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string. The most common way to achieve that is with what's called base64.
Yes, you can use PNG to JSON Encoder on any operating system that has a web browser.
you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
This might get you started:
import json
import base64
data = {}
with open('some.gif', mode='rb') as file:
img = file.read()
data['img'] = base64.encodebytes(img).decode('utf-8')
print(json.dumps(data))
Python 2
As the base64.encodebytes()
has been deprecated in base64, the code snippet above can be modified as follows:
import json
import base64
data = {}
with open('some.gif', mode='rb') as file:
img = file.read()
data['img'] = base64.b64encode(img)
print(json.dumps(data))
Then, use base64.b64decode(data['img'])
to convert back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With