Understand and extract data from a JSON array using Typescript

Here is a JSON response I received from a remote server:

{
  "string": [
    {
      "id": 223,
      "name": "String",
      "sug": "string",
      "description": "string",
      "jId": 530,
      "pcs": [{
        "id": 24723,
        "name": "String",
        "sug": "string"
      }]
    }, {
      "id": 247944,
      "name": "String",
      "sug": "string",
      "description": "string",
      "jlId": 531,
      "pcs": [{
        "id": 24744,
        "name": "String",
        "sug": "string"
      }]
    }
  ]
}

To extract and list the "name" & "description" values from this response, I have created the following code:

interface MyObj {
  name: string
  desc: string
}
let obj: MyObj = JSON.parse(data.toString());

I'm now looking for help on how to display the extracted "name" and "description" in a format that can be easily shown on a webpage.

Answer №1

Your parsed data has an incorrect type assigned to it. It should be structured like this:

interface MyObj {
  name: string
  description: string
}

let obj: { string: MyObj[] } = JSON.parse(data.toString());

Instead of just MyObj, make sure you have an object with a property named string that contains an array of MyObj. This will allow you to access the data in this format:

console.log(obj.string[0].name, obj.string[0].description);

If you prefer, you can define an interface for the structure instead of using an anonymous type:

interface MyRootObj {
  string: MyObj[];
}

let obj: MyRootObj = JSON.parse(data.toString());

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

I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with. I am trying to figure out how to retrieve data from an Angular form for a small web resource ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Tips on sending nested JSON data to a Spring Controller

My JSON structure looks like this: "Organization":{ "legalname" : "", "dba" : "", "fein" : "" } In my Jquery code, I make an AJAX call like this: $.ajax({ type: "POST", con ...

"What is the best way to specify a type for the src attribute in a tsx file within a

<Image src= { sessionData?.user.image} alt="user" width={100} height={100} />` An issue has been encountered: There is a type error stating that 'string | null | undefined' cannot be assigned to type 'stri ...

Ways to retrieve JSON information and incorporate it into an if statement in this specific scenario

Here is the AJAX function code I have written: $('#request_form').submit(function(e) { var form = $(this); var formdata = false; if (window.FormData) { formdata = new FormData(form[0]); } var formAction = form.attr( ...

Invoke the submit function of a form located outside a Material UI dialog from within the dialog

I'm facing an issue with a nested form scenario. The <form/> inside another form is displayed as a Material UI dialog and rendered in a separate portal in the DOM. /* SPDX-FileCopyrightText: 2021 @koistya */ /* SPDX-License-Identifier: MIT */ i ...

Using `useState` within a `while` loop can result in

I'm working on creating a Blackjack game using React. In the game, a bot starts with 2 cards. When the user stands and the bot's card value is less than 17, it should draw an additional card. However, this leads to an infinite loop in my code: ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

What is the best way to click on a particular button without activating every button on the page?

Struggling to create buttons labeled Add and Remove, as all the other buttons get triggered when I click on one. Here's the code snippet in question: function MyFruits() { const fruitsArray = [ 'banana', 'banana', & ...

Is it possible to modify the Angular global error handler to accept additional parameters besides just the error object?

After exploring the capabilities of https://angular.io/api/core/ErrorHandler, I have found that it allows me to override the global error handler with an error object. I appreciate how I can easily define my own global error handler and use it wherever nec ...

The connection named "default" was not located

Error ConnectionNotFoundError: Connection "default" was not found. I encountered this error when I implemented the dependency inversion principle in my project. ormconfig.json { "name": "default", "type": " ...

Isotope: Real-time JSON content extracted from Google Spreadsheet

My goal is to populate an Isotope list using data from a Google Spreadsheet JSON. However, I'm facing issues with the animation and sorting functionality once I add the JSON. Although I have verified that the JSON/JavaScript for loading it works, I am ...

Retrieve a collection of nested dictionaries containing flask and angular data

In my app development journey with flask and ionic(angular), I'm working on returning a JSON list. Here's the python code snippet: def get-stocks(): # Select all stocks cursor.execute("""SELECT * FROM `tbl_symbol_index`"" ...

Guide to duplicating a json file using the webpack duplication tool and integrating the version from the package.json file

I am attempting to move my manifest.json file (which is used for web extensions) into the build/ directory and replace the version within that file with the version stated in the package.json file using webpack's DefinePlugin. Is there a way for me t ...

Python Scrap Data Project

I attempted to extract data using Xpath, but unfortunately, it was unsuccessful. My aim is for the code to retrieve information from specific columns on the website "https://www.destatis.de/DE/Themen/Gesellschaft-Umwelt/Bevoelkerung/Geburten/Tabellen/leben ...

A class in Typescript containing static methods that adhere to an interface with a string index

Take a look at this code snippet: interface StringDoers { [key: string]: (s: string) => void; } class MyStringDoers implements StringDoers { public static print(s: string) { console.log(s); } public static printTwice(s: string) { conso ...

Transferring JSON data using AJAX

I am having trouble sending JSON via AJAX using pure JavaScript. While I can successfully retrieve values back from PHP, I am struggling to retrieve a specific JSON array. var mname = ["john", "mary", "eva"]; var fname = 678; clicked_keyword_test = {"last ...

Conceal the absence of a value within an array

I need assistance with handling an array of parameters: $fields = [ 'idutente' => $_POST['acf']['field_60084ad3970a8'] ?? 0, 'nome' => $_POST['acf']['field_6050d30f14572'], ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...

What are the best methods for encoding and decoding query parameters?

Here is the current implementation of my Express.js function "Restore objects pickled into JSON strings": router.post('/restore', json_parser, function(request, response, next) { console.log('router.post /load'); console.log(&apo ...