gpt4 book ai didi

python - 我想将base64转换为json

转载 作者:行者123 更新时间:2023-11-28 19:03:51 25 4
gpt4 key购买 nike

我想从 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}

最佳答案

你可以这样做:

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.jsonopen 函数中:

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)

关于python - 我想将base64转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com