Is it possible to extract JSON data using axios and TypeScript and convert it into a PascalCase model structure

I have the following type:

export type Model = {
  Id: number,
  Name: string
}

and also a JSON response like this:

{"id": 0, "name": "User"}
.

When I parse that response using Axios (

const response = await Axios.get<Model>(source)
), I end up with the following object:

Id: undefined Name: undefined id: 0 name: "User"

How can I correctly parse the response to match the PascalCase model?


`

Answer №1

To achieve this task, you have various options available but one crucial aspect to address is correcting the data types as they are currently inaccurate. Additionally, manual transformation of your result object is required.

Currently, the data types indicate that Axios.get will provide a model with keys named Id and Name, which is incorrect since it should actually return a model with keys named id and name. While you can convert the result accordingly, it is essential to rectify the initial return value information.

Once the data types are corrected, you can proceed to transform the JSON response into the desired model format. One approach is utilizing lodash, which simplifies this conversion process.

An illustrative example could be structured as follows:

export type Model = {
  Id: number,
  Name: string
}

// Obtain the raw response adhering to the accurate response type
const response = await Axios.get<{ id: number, name: string }>(source);

// Convert it into a new object aligning with the desired type
const model: Model = _.mapKeys(response,
  (value, key) => _.upperFirst(key) // Converting camelCase keys to PascalCase
);

Keep in mind that there are numerous alternatives for the final transformation step. The above example serves as just one potential solution. It may also be beneficial to consider implementing validation initially to ensure the response data conforms to your expectations, especially if there is a risk scenario involved.

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

Creating a rake migration file automatically for JSON data

When using sqlite3 with Rails 4.2.0, I encountered an error while running rake db:migrate. The issue seems to be with the migration file containing: t.json :blah when it should be t.column :blah, :json My question is, "How can I ensure the migration file ...

Displaying webAPI response on TextView in Android

I am new to Android development and I have been struggling with calling a web API on button click in my sample application. Although I am able to successfully retrieve the response in Android format, I am facing challenges in displaying these values in a T ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...

Retrieve the HTML data from a form created with Angular

Here is an example of an Angular form: <div #myForm [formGroup]="myForm"> <select formControlName="productName" class="form-control"> <option value="">Select</option&g ...

Combining various DTOs in a seamless manner for validation in TypeScript is made easy with the class-validator fusion technique

As I delved into my NestJS project, I found the class-validation aspect to be quite bothersome. It felt like I was constantly repeating the same classes with identical decorators. For example: export class DTO1 { @IsDefined() @IsString() name: ...

Tips for properly sending an array containing objects in JSON format using Swift for iOS development

As a beginner, I am trying to grasp the concept of sending an array with objects. Does the server recognize arrays like Int, Strings, or Booleans? Do I need to convert the array into a string for JSON data? There seems to be something I'm missing. va ...

Processing data on the server side using Dojo's Ajax functionality

I am struggling to figure out how to read JSON data sent from the client side to a server running a cgi-bin Perl script. Despite searching for examples, I have been unable to find a solution. The dojo version I am using is 1.8.1... Although the request se ...

Transforming Java objects into JSON using Jackson library

Here's the JSON format I'm aiming for: { "information": [{ "timestamp": "xxxx", "feature": "xxxx", "ean": 1234, "data": "xxxx" }, { "timestamp": "yyy", "feature": "yyy", "ean": 1234 ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Resizing the elements within an iframe: Troubleshooting problems with embedding Bandcamp players

My goal is to embed a Bandcamp music player on my WordPress blog page, but I'm facing a challenge. The maximum width of the current player is 700px and I need it to be 900px. After consulting with someone at Bandcamp, they directed me to the old versi ...

Combining identical data in JSON and PHP

I am facing an issue with a JSON data set that contains duplicate ord_name, cust_id, and Ord_num values. {"orders":[{"id":"1","ord_name":"Nestea Bottle","ord_desc":"Nestea in a bottle","ord_price":"15","ord_qty":"2","customer_id":"54feec24bff73","ord_num" ...

Issue with the onClick event in next.js and TypeScript

While working on the frontend development of an app, I encountered a strange issue with the onClick function. The error message I'm seeing is: Type '(e: SyntheticEvent<Element, Event>) => void' is not assignable to type 'Custom ...

Issues arise when attempting to use Axios and Express within a React App, resulting in a "Cannot POST /" error

I am currently working on setting up a basic form to send emails, but I keep encountering the following error: Error: Cannot POST / The structure of my App.js file using Create React App is as follows: import React, { Component } from 'react'; ...

Challenges with TypeScript's typeof operator and instantiation of classess

Discussing the scenario of a map setup: const map = { a: ClassA, b: ClassB, c: ClassC, } The purpose of this map is to link different classes together. There exists a function that returns an instance of a class based on a key in the map ...

Error: An instance of the Java Long class cannot be deserialized from a START_ARRAY token

Having trouble deserializing this JSON: { "login": "tamtoum", "lastName": "brahim", "emailAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0d1d0e0706022f0e1e1e1c1c410c0002">[email protected]</a>", "fir ...

Parsing a datetime string without altering the format

My WebAPI controller is receiving a formatted datetime variable and I simply want to retrieve the string value without any datetime format manipulation on deserialization. Here's the snippet of my code: [HttpPost] public IHttpActionResult GetByDateTim ...

Uniqueness in TypeScript tuples: ensuring no duplicates

Solving the Problem Imagine we have a React component called X that requires input from properties Input. These properties include a field known as bounds. The bounds consist of a tuple containing 1-4 string literals: alpha, beta, gamma, delta. Objective ...

Caution: The Vue Class Based Component is signalling that a property is not defined on the instance, yet it is being

I've been experimenting with creating a Vue component using vue-class-component and TypeScript. I referenced the official documentation here: https://github.com/vuejs/vue-class-component. Despite defining the data within the class as shown below, I en ...

Utilize Angular and a store to generate an HTTP request on the local db.json file

Trying to make an HTTP request on a local db.json file has been a challenge for me. (using a store in Angular with the Angular CLI). Unfortunately, my knowledge on this is limited: I have included a snippet of code from my service below: view image descri ...

Unable to receive AJAX response for the GET request

I am attempting to achieve the following: Upon clicking on H1, jQuery is supposed to retrieve information for a specific key from the server and display it in a prompt. The PHP code resides in server.php. $link = mysql_connect("mysql.hostinger.com.ua", "_ ...