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

无法从Google Cloud Vision API(Node.js库)响应中提取JSON数据

问题原因及解决方案

1. JSON.parse报错原因

Google Vision Node.js SDK返回的response已经是解析完成的JavaScript对象,无需再次调用JSON.parse。你将对象传入JSON.parse时,方法会自动将对象转为[object Object]字符串,解析到第二个字符o时不符合JSON语法,因此抛出语法错误。

2. for...in遍历报错原因

for...in遍历数组时返回的是索引的字符串形式,而非数组元素本身。你代码里的page实际是"0"、"1"这类字符串,自然不存在blocks属性,因此报类型错误。
遍历数组可选用以下几种正确写法:

  • 你已经验证可用的索引式for循环
  • 更简洁的for...of循环:
const fullTextAnnotation = response[0].fullTextAnnotation;
const allBlocks = [];
for (const page of fullTextAnnotation.pages) {
  for (const block of page.blocks) {
    allBlocks.push(block);
  }
}
  • 数组内置方法(代码更精简):
const allBlocks = fullTextAnnotation.pages.flatMap(page => page.blocks);

常用数据提取技巧

如果仅需要提取识别到的全部文本内容,无需逐层遍历符号,可直接读取fullTextAnnotation下的text字段:

const fullText = response[0].fullTextAnnotation.text;

如果需要结构化提取段落、单词等信息,按层级遍历对应字段即可:pages → blocks → paragraphs → words → symbols。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:05