JSON嵌套属性访问问题:如何提取Cognitive Services返回结果的text字段
解决Cognitive Services JSON提取text属性并拼接的问题
嘿,我懂你现在的困扰——刚学JSON一周,面对Cognitive Services返回的嵌套结构确实容易懵。你之前用逗号或括号访问失败,大概率是没处理好数组的遍历问题,毕竟这个JSON里的regions、lines、words都是数组类型,得一层一层拆开遍历才行。
先补全你示例里省略的完整JSON结构(这是OCR接口返回的标准格式),方便你理解层级:
{ "language": "en", "orientation": "Up", "textAngle": 0, "regions": [ { "boundingBox": "12,106,781,327", "lines": [ { "boundingBox": "14,108,777,59", "words": [ { "boundingBox": "14,108,153,59", "text": "Hello" }, { "boundingBox": "175,108,143,59", "text": "World" } ] }, { "boundingBox": "16,188,773,62", "words": [ { "boundingBox": "16,188,223,62", "text": "Cognitive" }, { "boundingBox": "247,188,183,62", "text": "Services" } ] } ] } ] }
核心思路非常简单:逐层遍历嵌套数组,把所有text属性收集起来,最后拼接成字符串。下面给你两种常用场景的代码示例:
前端JavaScript(直接用于界面展示)
// 假设response是你从Cognitive Services拿到的已解析JSON对象 const response = { /* 上面的完整JSON内容 */ }; const allTexts = []; // 遍历regions数组 response.regions.forEach(region => { // 遍历当前region下的lines数组 region.lines.forEach(line => { // 遍历当前line下的words数组 line.words.forEach(word => { allTexts.push(word.text); }); }); }); // 用空格拼接成完整字符串(你可以换成逗号、换行符等) const displayText = allTexts.join(' '); // 直接渲染到界面,比如React里可以这样写: // <div>{displayText}</div> console.log(displayText); // 输出: "Hello World Cognitive Services"
后端Python(如果是后端处理后返回给前端)
# 假设response是已解析后的JSON字典 response = { /* 上面的完整JSON内容 */ } all_texts = [] for region in response['regions']: for line in region['lines']: for word in line['words']: all_texts.append(word['text']) # 拼接成字符串 display_text = ' '.join(all_texts) print(display_text) # 输出: Hello World Cognitive Services
为啥你之前访问失败?
因为regions、lines都是数组(带[]标记),不能直接用response.regions.lines这种方式访问,必须先遍历数组里的每一项,或者用索引取单个元素(比如response.regions[0].lines),但遍历更稳妥——毕竟接口可能返回多个区域的文本。
内容的提问来源于stack exchange,提问作者Thuong Vo Tinh
相关产品推荐
相关产品推荐

