问题描述
我正在JavaScript Web应用程序中使用Microsoft Azure Cognitive Services文本识别API。
从图像中成功提取文本后,将给出如下响应:
{ "language": "en","textAngle": 0,"orientation": "Up","regions": [ { "boundingBox": "238,220,3547,2476","lines": [ { "boundingBox": "415,104,45","words": [ { "boundingBox": "415,"text": "096" } ] },{ "boundingBox": "473,374,2854,202","words": [ { "boundingBox": "473,418,1092,139","text": "Storehouse" },{ "boundingBox": "1635,410,149,142","text": "is" },{ "boundingBox": "1854,406,666,170","text": "always" },{ "boundingBox": "2596,731,183","text": "moving" } ] },{ "boundingBox": "445,614,2744,200","words": [ { "boundingBox": "445,641,788,173","text": "forward," },{ "boundingBox": "1310,640,350,145","text": "and" },{ "boundingBox": "1739,668,400,113","text": "Now" },{ "boundingBox": "2200,621,369,151","text": "this" },{ "boundingBox": "2647,542,147","text": "issue" } ] } ] } ] }
我希望能够分别获取'text'的值来生成字符串,例如:'仓库总是在向前发展,现在这个问题 ...
请问如何使用JavaScript进行此操作?我想尝试访问嵌套的“文本”值会感到困惑。尝试了for-for-for循环而没有喜悦!
API确实使用以下方法将JSON响应解析为字符串:
JSON.stringify(data,null,2);
“ data”是JSON响应的名称。我知道必须先将其解析为数组,然后才能进行任何操作,但是不确定。
我可以使用jQuery。
干杯!
解决方法
一种迭代,简单的解决方案。
const tmp = {
"language": "en","textAngle": 0,"orientation": "Up","regions": [
{
"boundingBox": "238,220,3547,2476","lines": [
{
"boundingBox": "415,104,45","words": [
{
"boundingBox": "415,"text": "096"
}
]
},{
"boundingBox": "473,374,2854,202","words": [
{
"boundingBox": "473,418,1092,139","text": "Storehouse"
},{
"boundingBox": "1635,410,149,142","text": "is"
},{
"boundingBox": "1854,406,666,170","text": "always"
},{
"boundingBox": "2596,731,183","text": "moving"
}
]
},{
"boundingBox": "445,614,2744,200","words": [
{
"boundingBox": "445,641,788,173","text": "forward,"
},{
"boundingBox": "1310,640,350,145","text": "and"
},{
"boundingBox": "1739,668,400,113","text": "now"
},{
"boundingBox": "2200,621,369,151","text": "this"
},{
"boundingBox": "2647,542,147","text": "issue"
}
]
}
]
}
]
}
const outputWords = []
tmp.regions.forEach(region =>
region.lines.forEach(line =>
line.words.forEach(word =>
outputWords.push(word.text)
)
)
)
console.log(outputWords.join(' '))