在python3中將jpg轉成base64並寫入json

import base64

with open('./aa.jpg', 'rb') as f:
    qrcode = base64.b64encode(f.read()).decode()
    """
    #The following is wrong, when json.dumps is run, it will raise error "TypeError: Object of type 'bytes' is not JSON serializable"
    """
    #qrcode = base64.b64encode(f.read())
    
images = []
element1 = {'name': 'http://www.baidu.com',
            'data': qrcode
           }
element2 = {'name': 'http://www.baidu.com',
            'type': 1
           }
images.append([element1, element2])
print('images:{}'.format(images))
json_str = json.dumps(images)
print('json_str:{}'.format(json_str))
#convert JSON object to str
data = json.loads(json_str)
print('data:{}'.format(data))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章