Converting JSON array to custom object array in TypeScript

As a newcomer to this area, please excuse any inaccuracies in my language. Don't hesitate to ask for more details if needed.

I currently have some TypeScript interfaces:

export interface Item {
    id: string
    type: string
    state: string
}

export interface ItemResponse {
    someData1: string
    someData2: string
    itemListResponse: Array<Item> // essentially a JSON string containing serialized Items in an array
}

The ItemResponse is being populated through a fairly successful call to an external service:

The outcome is a series of ItemResponses. For now, let's assume the size of the ItemResponse array is 1, although there are multiple Items within the itemListResponse array.

The itemListResponse is essentially just a JSON string:

"[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"

How can I convert this into an array of Items?

I believe I understand how to parse from JSON to a single object, but I'm uncertain about managing arrays.

Answer №1

@SteveSmith42 is right - you need to utilize JSON.parse for this task. A simple example would look like this:

dataArray =  "[{"id":"example1", "type":"example1", ...}, {"id":"example2",.... },...]"
<Item[]> JSON.parse(dataArray)

Of course, this code lacks validation of the response, which is not recommended. It is advisable to add some form of data validation:

dataArray =  "[{"id":"example1", "type":"example1", ...}, {"id":"example2",.... },...]"

var output;
try {
   itemListData = <Item[]>JSON.parse(dataArray);

   if(!itemListData.has("id") ||
      !itemListData.has("type") ||
      !itemListData.has("state")){

      throw "Invalid Item";
   }
} catch (error){

}

Alternatively, consider using a JSON Schema validator such as ajv.

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

Sequence of HTML elements arranged in a stack

Recently, I came across a useful jQuery tutorial called "jQuery for Absolute Beginners: Day 8". In this tutorial, there is an interesting code snippet that caught my attention: $(function() { $('.wrap').hover(function() { $(this).childre ...

Vue Router is failing to match a URL that contains numerous dynamic parameters

I've been working on adding a nested url to my routes and have encountered an issue with the last route in my code. Every other route seems to be functioning properly. I attempted to nest the urls using the children property, but it wasn't succe ...

Organize library files into a build directory using yarn workspaces and typescript

When setting up my project, I decided to create a yarn workspace along with typescript. Within this workspace, I have three folders each with their own package.json /api /client /lib The main goal is to facilitate code sharing between the lib folder and b ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

The request to http://localhost:8080 from http//:localhost:3000 has been restricted due to CORS policy blocking access. This is due to the absence of the 'Access-Control-Allow-Origin' header in the

const fileStorage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "images"); }, filename: function (req, file, cb) { cb(null, uuidv4()); }, }); const fileFilter = (req, file, cb) => { if ( file.mi ...

What is the best way to switch routes in redux saga upon successful login?

Greetings! I'm a newcomer to React and I've been using React hooks and redux-saga for my project. I have a requirement where I need the router to navigate to /home upon successful login. I attempted to achieve this using connected-react-router an ...

Error: jQuery Validation not triggering in Bootstrap modal window

My attempts to use jQuery Validation for form validation inside a modal have hit a dead end. The validation doesn't trigger at all, not even an error message is displayed. Upon debugging, a warning emerged: No elements selected for validation; retu ...

Retrieving the output of a parent computed method in VueJS, using a child component

I am facing difficulties in passing the dynamically changing value of a computed method to my child component. I am creating a button component with different save states, but the button always remains stuck on one state and does not update according to th ...

Saving an array of key-value pairs in local storage

I'm attempting to save an array in local storage using the following code: var tempval = []; tempval['key'] = 1; localStorage.setItem("Message", JSON.stringify(tempval)); However, when I check local storage, it only sho ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

Creating a dynamic canvas with a three-dimensional model using three.js: A step-by-step guide

I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation. The issue arises wh ...

Working towards ensuring my website is responsive

Hello, I am a CSS beginner currently working as an intern. My task is to make a website's CSS compatible with Internet Explorer, and then make it responsive and scalable. Essentially, the design should retain its appearance when the window size change ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

Error message: "No elements were found in Ember.js jQuery cycle slideshow"

As I transition a traditional HTML site to an Ember.js application, I encountered a problem with the jQuery Cycle slideshow plugin. With approximately 10 slideshows on the site, I aimed to create a reusable partial to pass data to. Although the data passi ...

restrict the maximum character count in regex

The string can consist of a single number or multiple numbers separated by "-", but the total character count must not exceed 6. Examples of valid strings 5 55-33 4444-1 1-4444 666666 Examples of invalid strings -3 6666- 5555-6666 My initial regex / ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Trying to utilize RegEx for my project, but feeling stuck on how to solve my problem

^\d{1,12}$|(?=^.{1,15}$)^\d+\.\d{1,2}$ This is the current regular expression I am using. I need to adjust the maximum limit to 100,000,000,000 with an option for two decimal places. Additionally, I would like users to be able to inpu ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Why do we often encounter a "SyntaxError: Unexpected token ;" error when a seemingly normal semicolon is present in distribution files?

Currently, I am in the process of developing a newsletter subscription API using node.js and typescript. This project involves my first experience with typeorm and PostgreSQL. Following several tutorials, I configured typeorm and created the entity types a ...

Retrieving user input in a JavaScript/React app

I'm currently developing a search feature for my website using Algolia. When the user types in their search term, the results are updated to show relevant matches as they go. Here is an example below of what I am working on: https://codesandbox.io/s ...