You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将Google Vision API返回的数据集转换为JSON文件?

把Google Vision API数据转成JSON文件的方法

嘿,作为Python新手遇到这个问题完全正常,我来一步步帮你搞定这件事!

第一步:把原始数据转换成合法的Python数据结构

你给出的数据集格式是Google Vision API返回的标注结果,但不是标准的Python可识别格式,我们先把它改成列表嵌套字典的形式(这是Python和JSON最兼容的数据结构之一):

# 把你的原始数据补全并转换成Python结构
vision_labels = [
    {
        "mid": "/m/02wbm",
        "description": "food",
        "score": 0.8716073632240295,
        "topicality": 0.8716073632240295
    },
    {
        "mid": "/m/01ykh",
        "description": "cuisine",
        "score": 0.848469614982605,
        "topicality": 0.848469614982605
    },
    {
        "mid": "/m/01f5gx",
        "description": "eating",
        "score": 0.XXX  # 这里把你没写完的分数值补上就行
    }
]

第二步:用Python内置的json模块生成JSON文件

Python自带了json模块,不需要额外安装,直接用它把Python数据写入JSON文件:

import json

# 定义要保存的JSON文件名,比如叫vision_results.json
output_filename = "vision_results.json"

# 打开文件并写入数据
with open(output_filename, "w", encoding="utf-8") as file:
    # indent=4 让JSON内容排版更美观,ensure_ascii=False支持中文(如果有需要的话)
    json.dump(vision_labels, file, indent=4, ensure_ascii=False)

print(f"搞定啦!JSON文件已经保存到 {output_filename}")

额外小技巧:如果直接从API获取响应

如果你是直接调用Google Vision API拿到的响应,其实可以直接提取里面的label_annotations字段(就是你给出的数据集),不用手动整理:

# 假设你已经通过API获取到了响应对象response
import json

# 直接提取标注数据
label_data = response["label_annotations"]

# 写入JSON文件
with open("vision_api_results.json", "w", encoding="utf-8") as file:
    json.dump(label_data, file, indent=4, ensure_ascii=False)

这样执行完代码,你就能在当前目录下找到生成的JSON文件啦!

内容的提问来源于stack exchange,提问作者Boris Huang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:47:44