Extract particular elements from a nested JSON response in order to convert them into a string

I am currently integrating Microsoft Azure Cognitive Services text recognition API into a JavaScript web application.

After successfully extracting text from an image, the response looks like this:


    {
      "language": "en",
      "textAngle": 0,
      "orientation": "Up",
      ...
    }

To create a coherent string with the value of 'text' in each case, such as: 'Storehouse is always moving forward, and now this issue...

How can I achieve this in JavaScript? Accessing nested 'text' values using for and for-of loops has been challenging!

The API converts the JSON response to a string using:

JSON.stringify(data, null, 2);

Once the response is parsed as an array, further steps are unclear to me. Any guidance on how to proceed would be appreciated.

I have access to jQuery if needed.

Thank you!

Answer №1

Here is a straightforward and step-by-step solution.

const data = {
  "language": "en",
  "textAngle": 0,
  "orientation": "Up",
  "regions": [
    {
      "boundingBox": "238,220,3547,2476",
      "lines": [
        {
          "boundingBox": "415,220,104,45",
          "words": [
            {
              "boundingBox": "415,220,104,45",
              "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,374,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,614,542,147",
              "text": "issue"
            }
          ]
        }
      ]
    }
  ]
}

const outputWords = []

data.regions.forEach(region => 
  region.lines.forEach(line => 
    line.words.forEach(word => 
      outputWords.push(word.text)
    )
  )
)

console.log(outputWords.join(' '))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error when trying to retrieve data from a three-dimensional array

I tried to implement a three-dimensional array in JavaScript, but I encountered an error message in Chrome: Error: Uncaught SyntaxError: Unexpected token [ This is the snippet of my JavaScript code: function ThreeDimensionalArray(iRows,iCols,iHig) { ...

transferring information from the Quill text editor to the Node.js server

Is there a way to send data from Quilljs on the frontend to node.js on the backend? I've been searching for examples, but haven't found anything related to the backend. I tried reading the documentation for Quilljs, but I'm still struggling ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

Changing the text color and background color of a span element when a ng-click event is triggered

There are two buttons, Today and Tomorrow, each with an ng-click function. By default, the button background color is white and text color is red. When the Today button is clicked, the background color changes to blue and the text color changes to white. ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

UI-Router causing issues with AngularJS anchorScroll functionality

Currently, I am utilizing ui-router and attempting to implement automatic scrolling within the controller. However, it seems that anchorScroll function is not working as expected. My assumption is that it may be due to having two '#' symbols in t ...

Can you explain the distinctions among “assert”, “expect”, and “should” in the Chai framework?

Can you explain the variations between assert, expect, and should? How do you know when to utilize each one? assert.equal(3, '3', '== turns values into strings'); var foo = 'bar'; expect(foo).to.equal('bar' ...

What could be the reason for the image not showing up on react?

When I try to retrieve the base64 image from the server, it is not displaying properly. Here is the error message I am getting: GET data:image/png;base64,{base64 string} net::ERR_INVALID_URL <img src={data?.gameIcon} alt="" className={st ...

How can we prevent checkbox and radio buttons from being triggered by accidental taps on the surrounding area on touch-responsive devices?

On touch screen responsive devices, there seems to be an issue where clicking outside the checkbox or radio button (within about 8px) causes the checkbox or radio button to toggle. This problem only occurs on responsive touch devices and works fine on desk ...

Is it possible to display a React Component code within a <code> tag?

I am in the process of creating a tester page that allows users to interact with a library component and document how it is being used. Here is the library component: render = () => { let component = ( <Slider onSlid ...

Reset an Angular service's public variable

I recently started working with Angular and encountered an issue that I couldn't find a solution for on Google or Stack Overflow. I believe my problem lies in not knowing what to search for. Here is the code snippet causing trouble: JSFiddle HTML &l ...

Utilize PHP, JSON, and JavaScript to dynamically insert personalized information into HTML

Struggling, I turn to this site for help despite the dislike for "spot my mistake" code. My website urgently needs access to user-specific data from a PHP database, then convert that data into a JSON file and display it in an HTML header. The database cont ...

Guidelines on executing a function after page load in meteor

Currently, I am using cursor.observeChanges to monitor new records inserted in MongoDB and trigger a notification when that happens. The issue I am facing is that these notifications are popping up when my app is loaded for the first time or when I navigat ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

What are the steps to create a dictionary app utilizing the Oxford Dictionary API?

The code snippet provided in the documentation returns a JSON result, but I am only interested in extracting the meaning of the word. Can someone guide me on how to specifically extract the meaning without fetching the entire JSON file? As a beginner in an ...

What is the best way to format 100K to appear as 100,000?

function formatNumberWithCommas(num) { return num >= 1000 ? `${Number.parseFloat((num).toFixed(3))}` : num; } ...

Webpack attempts to duplicate files prior to compilation but I am anticipating the opposite outcome

I needed the copy plugin to run after compilation, which seemed like the logical order. However, I found myself having to compile using webpack twice every time in order to get the fresh version on production. It wasn't until later that I realized it ...

React/Next Component Changes State and Clears it in useEffect

Currently, I am faced with an issue while attempting to fetch data from an API. The problem arises during the rendering process since the useEffect function is being called multiple times. Surprisingly, everything works perfectly fine during the initial pa ...

When using PHP to work with JSON arrays, it is necessary to specify an index in order to retrieve the value

My json array has the following structure: [{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}] Typically, I access values in the array like this: $configarray = json_deco ...

Most effective method for integrating a JS module across all browsers

I have created a robust library that I want to integrate into a different web project. This library handles all its dependencies and consists of js, css, and html files. My ideal scenario would be to package it as an npm module and simply use import to in ...