我想将base64转换为json

时间:2018-03-25 08:23:59

标签: python json binary base64

我想从base64转换为json。现有文件是.jpg,目的是在一个文件夹中加载多个文件并将它们组合成一个json。

import base64
import json
import os

directory = os.listdir('C:/users/user/desktop/k-means/image')
os.chdir('C:/users/user/desktop/k-means/image')
data={}

for file in directory:
    open_file = open(file,'rb')
    image_read = open_file.read()
    image_64_encode = base64.encodestring(image_read)
    data[""] = image_64_encode.decode('ascii')
    with open('words.json', 'w', encoding="utf-8") as make_file:
        print(json.dumps(data))

所需的输出如下。如何修改我的代码?

{"data": 
"AAAAAGHLd/f39/clOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", "label": 5}
{"data": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", "label": 0}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

import base64
import json
import os
from pprint import pprint

directory = os.listdir('C:/users/user/desktop/k-means/image')
os.chdir('C:/users/user/desktop/k-means/image')
data={}

for file in directory:
    base = os.path.basename(file)
    data["label"] = base
    open_file = open(file,'rb')
    image_read = open_file.read()
    image_64_encode = base64.encodebytes(image_read)
    data["data"] = image_64_encode.decode('ascii') 
    final_data = json.dumps(data)
    final_data = json.loads(final_data)
    pprint(final_data)

#output: {"data": "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFB...", "label": "Capture.JPG"} 

注意encodestring是自Python3.1以来不推荐使用的别名,我使用的是encodebytes

要将此final_data写入json文件,必须将循环包含在 words.json open函数中:

with open('words.json', 'w') as make_file:
    for file in directory:
        base = os.path.basename(file)
        data["label"] = base
        open_file = open(file,'rb')
        image_read = open_file.read()
        image_64_encode = base64.encodebytes(image_read)
        data["data"] = image_64_encode.decode('ascii') 
        final_data = json.dumps(data)
        make_file.write(final_data)