如何解析Google Cloud OCR输出的类JSON格式并转为标准JSON?
解析Google Cloud OCR的类JSON格式并转换为标准JSON
问题描述
从Google Cloud OCR获取的数据呈现为一种类JSON格式,但键无引号、缺少逗号,示例如下:
text_annotations { description: "," bounding_poly { vertices { x: 485 y: 237 } vertices { x: 492 y: 237 } vertices { x: 492 y: 266 } vertices { x: 485 y: 266 } } }
获取该数据的Python代码如下:
from google.cloud import vision import io client = vision.ImageAnnotatorClient() feature = vision.Feature( type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) response = client.text_detection(image=image) print(response)
需要找到简便方法解析该格式或转换为标准JSON。
解决方案
你看到的不是类JSON格式,而是Protocol Buffers(Protobuf)的文本序列化形式。Google Cloud Vision的API返回的response是Protobuf消息实例,直接print()会输出这种文本格式,无需手动添加引号和逗号,用官方提供的工具就能直接转成标准JSON或Python字典:
方法1:转换为标准JSON字符串
导入google.protobuf.json_format中的MessageToJson方法,直接将Protobuf对象转为JSON:
from google.cloud import vision import io from google.protobuf.json_format import MessageToJson client = vision.ImageAnnotatorClient() feature = vision.Feature( type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) path = "你的图片路径" with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) response = client.text_detection(image=image) # 转换为标准JSON并打印 print(MessageToJson(response))
方法2:转换为Python字典
如果需要进一步处理数据,可以用MessageToDict将Protobuf对象转为Python字典,之后可按需转成JSON或直接操作:
from google.cloud import vision import io from google.protobuf.json_format import MessageToDict import json client = vision.ImageAnnotatorClient() feature = vision.Feature( type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) path = "你的图片路径" with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) response = client.text_detection(image=image) # 转换为Python字典 response_dict = MessageToDict(response) # 可选:将字典转为格式化后的JSON字符串 json_str = json.dumps(response_dict, indent=2) print(json_str)
这两种方法都是官方支持的最优方案,避免了手动解析的繁琐和出错风险。
内容的提问来源于stack exchange,提问作者Pondzik
相关产品推荐
相关产品推荐

