gpt4 book ai didi

javascript - 如何从 Google Cloud Vision API 生成的嵌套 JSON 中获取特定数据

转载 作者:行者123 更新时间:2023-11-30 20:52:30 24 4
gpt4 key购买 nike

我正在开发一个系统并尝试从 Google Cloud Vision API 生成的 JSON 中获取特定数据,并希望在 html 上显示关键字。您可以看到嵌套的 JSON(数据)如下所示。在描述中,我想在我的 html 中显示“狗”。

{
"responses": [
{
"labelAnnotations": [
{
"mid": "/m/0kpmf",
"description": "dog breed",
"score": 0.9408917
},
{
"mid": "/m/0bt9lr",
"description": "dog",
"score": 0.91643894
},
{
"mid": "/m/01z5f",
"description": "dog like mammal",
"score": 0.86234033
},
{
"mid": "/m/02kysw",
"description": "spaniel",
"score": 0.84150785
},
{
"mid": "/m/02xl47d",
"description": "dog breed group",
"score": 0.83750784
},
{
"mid": "/m/05mqq3",
"description": "snout",
"score": 0.7590523
},
{
"mid": "/m/01p2lr",
"description": "american cocker spaniel",
"score": 0.7300941
},
{
"mid": "/m/02wcn0z",
"description": "russian spaniel",
"score": 0.6928253
},
{
"mid": "/m/03ht9m",
"description": "field spaniel",
"score": 0.6872984
},
{
"mid": "/m/02wbgd",
"description": "english cocker spaniel",
"score": 0.65664136
}
]
}
]
}

我写了下面的 javascript 代码,但仍然是“未定义”的答案

document.getElementById("demo").innerHTML = data.responses;

仅供引用,

data

是来自 JSON(谷歌视觉 API)的整体结果。非常感谢您的大力帮助!!

最佳答案

要只获得一个与“dog”一词匹配的结果,您可以使用 Array.prototype.find()

要获得包含单词“dog”的多个结果,您可以使用 Array.prototype.filter()结合 String.prototype.match()new RegExp(pattern[, flags])

const json = {"responses": [{"labelAnnotations": [{"mid": "/m/0kpmf","description": "dog breed","score": 0.9408917},{"mid": "/m/0bt9lr","description": "dog","score": 0.91643894},{"mid": "/m/01z5f","description": "dog like mammal","score": 0.86234033},{"mid": "/m/02kysw","description": "spaniel","score": 0.84150785},{"mid": "/m/02xl47d","description": "dog breed group","score": 0.83750784},{"mid": "/m/05mqq3","description": "snout","score": 0.7590523},{"mid": "/m/01p2lr","description": "american cocker spaniel","score": 0.7300941},{"mid": "/m/02wcn0z","description": "russian spaniel","score": 0.6928253},{"mid": "/m/03ht9m","description": "field spaniel","score": 0.6872984},{"mid": "/m/02wbgd","description": "english cocker spaniel","score": 0.65664136}]}]};

// seachString
const searchString = 'dog';

// one
document.getElementById('oneResult').innerHTML = json
.responses[0]
.labelAnnotations
.find(el => el.description === searchString)
.description;

// multiple
document.getElementById('multipleResult').innerHTML = json
.responses[0]
.labelAnnotations
.filter(el => el.description.match(new RegExp(searchString, 'i')))
.map(el => el.description)
.join(', ');
<p><b>One result</b>: <span id="oneResult"></span></p>

<p><b>Multiple results</b>: <span id="multipleResult"></span></p>

关于javascript - 如何从 Google Cloud Vision API 生成的嵌套 JSON 中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48019749/

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