【问题标题】:Can't extract JSON from API response - Google Cloud Vision API (Node.js library)无法从 API 响应中提取 JSON - Google Cloud Vision API(Node.js 库)
【发布时间】:2021-12-06 00:54:16
【问题描述】:

这可能是一个简单的 JSON 问题,但我正在努力使用 Node.js 上的 Google Vision API 从文本检测响应中提取数据

我得到的响应看起来像 JSON 数据(这里是原始响应的字符串示例):

[{webDetection: null, logoAnnotations: [], context: null, safeSearchAnnotation: null, 
fullTextAnnotation: {pages: [{blocks: [{blockType: TEXT, paragraphs: [{words: [{symbols:
 [{boundingBox: {normalizedVertices: [], vertices: [{x: 568, y: 0}, {x: 601, y: 1}, {x: 
600, y: 84}, {x: 567, y: 83}]}, property: {detectedBreak: null, detectedLanguages: 
[{languageCode: en, confidence: 0}]}, confidence: 0.9900000095367432, text: B}, 
{boundingBox: {normalizedVertices: [], vertices: [{x: 615, y: 0}, {x: 640, y: 0}, {x: 639,
 y: 83}, {x: 614, y: 83}]}, property: {detectedBreak: null, detectedLanguages: 
[{languageCode: en, confidence: 0}]}, confidence: 1, text: a}, {boundingBox: 
{normalized...

但是,当我尝试按如下方式解析它时,出现错误。

const jsonData = response[0].fullTextAnnotation;
const textAnnotation = JSON.parse(jsonData);

错误:SyntaxError:JSON 中位置 1 的意外标记 o

任何想法我做错了什么以及如何正确提取数据?

更新

我尝试将数据读取为数组和映射,这不适用于常规 for 循环,但如果我使用 int 循环,例如

不起作用:

const fullTextAnnotation = response[0].fullTextAnnotation;
  const pages = fullTextAnnotation.pages;
  const allBlocks = [];
  for (var page in pages) {
    const blocks = page.blocks;
    for (var block in blocks) {
      allBlocks.push(block);
    }
  }

有效:

const fullTextAnnotation = response[0].fullTextAnnotation;
  const pages = fullTextAnnotation.pages;
  const allBlocks = [];
  for (var i = 0; i<pages.length;i++) {
    const blocks = pages[i].blocks;
    for (var j = 0; j<blocks.length;j++) {
      allBlocks.push(blocks[j]);
    }
  }

当我使用常规 for 循环时,我得到一个错误: “字符串”类型上不存在属性“块”。

当我使用 int 循环时,blocks 属性正确显示为: 常量块:vision.protos.google.cloud.vision.v1.IBlock[]

我想这是我可以处理的事情,但是我肯定很好奇出了什么问题,因为我需要大量猜测才能找到解决方法。

【问题讨论】:

  • 您等待回复了吗?
  • 是的。我想要的信息肯定在里面。如果我查看字符串,我可以看到已识别的文本。

标签: node.js json google-cloud-platform


【解决方案1】:

如果没有完整的字符串,也没有前面的代码,很难判断,但看起来您可能在解析字符串之前获取了 fullTextAnnotation。我建议尝试解析 response 或 response[0],然后将 fullTextAnnotation 分配给 textAnnotation 变量。

如果您可以共享一个 console.log() 的响应、response[0]、相应的 JSON.parses(),然后可能是未解析的 response[0].fullTextAnnotation,那肯定会帮助我们诊断问题!

【讨论】:

  • 使用不同类型的 for 循环解决了我的问题,但是如果我以后有时间,我会看看我是否可以获取控制台日志来尝试找出 JSON 不解析出来的原因兴趣(虽然我的猜测是因为我试图解析 Vision API 对象)。
猜你喜欢
  • 1970-01-01
  • 2019-02-05
  • 2021-02-15
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 2018-07-15
相关资源
最近更新 更多