Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with has defined types, but the incoming JSON file uses "" for all values.

My only requirement is to change strings to numbers, nothing else.

Here's an example of the JSON input ->

{"sub_type": "0", "year": "2023", "peak": "N"}

Expected output:

{"sub_type": 0, "year": 2023, "peak": "N"}

I have attempted the following code snippet to achieve this:

    let cards: Array<Card> = pt_cards['data'];
    let tstCard: Card = JSON.parse(JSON.stringify(cards[0]), (key, value) => {
        if(!isNaN(value)) {
            return(key: value);
        }
        return value;
    });

Should I consider replacing the current Interface declaration instead?

Answer №1

Here's a method you can use:

JSON.parse(jsonString, (key, value) => {

   if (!isNaN(value)) {
      return Number(value);
   }

   return value;
});

This code snippet only converts the value to a number if it represents a number.

Answer №2

Why go through the hassle of using JSON.stringify just to turn around and use JSON.parse again? Check out this demonstration on typescript playground -

type t_card = {
  sub_type: number
  year: number
  peak: string
}

type t_serialized_card = {
  sub_type: string
  year: string
  peak: string
}

function stringToNumberExn(s: string): number {
  const n = Number.parseInt(s)
  if (Number.isNaN(n))
    throw Error(`stringToNumberExn: ${s} is not a number`)
  return n
}

async function getCards(): Promise<Array<t_card>> {
  // format as returned from backend
  const res: Array<t_serialized_card> = 
    await fetch("/path/to/cards").then(r => r.json())

  // map to desired format 
  return res.map(card => ({
    sub_type: stringToNumberExn(card.sub_type),
    year: stringToNumberExn(card.year),
    peak: card.peak
  }))
}

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

Trigger the click event on the ul element instead of the li element using jQuery

Is there a way to make the click event only affect ul tags and not all li elements using jQuery? <!-- HTML --> <ul class="wrap"> <li>test1</li> <li>test2</li> <li>test3</li> </ul> I attemp ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...

Clicking the ASP button does not trigger the onclick event when a web user control is included on the webpage

I have been working on a web form application that I developed using the visual studio template. The template includes a content placeholder that gets replaced by the content of each accessed page. One particular page, which contains server controls like t ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

Node.js encountering difficulty extracting JSON data

Within this JSON object, the Variable SNS holds valuable information that I need to extract and save in a new variable. `const sns = event.Records[0].Sns.Message;` The specific values I aim to retrieve are Trigger.Namespace, Trigger.Dimensions.value, an ...

What is the best method to utilize a promise to delay the execution of a function until the data is received and stored

Currently, I am facing an issue with my API where the model variable is returning undefined before any data is populated in the return_array. I am unsure of how to implement promises or another method to ensure that the variable waits for data to be fille ...

Issue - Basic Data Protection and Unscrambling - Node.js

I have been working on some basic code to encrypt and decrypt text, but I keep encountering an error when using the .final() function of createDecipherIV. I have tried experimenting with different encodings like Binary, Hex, and base64. Node Version: &apo ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup: ... props: ['customClass'], computed: { localClass: { get() { return this.custom ...

What is the best method to erase data from an AutoComplete Box when clicking?

I have incorporated the Material UI AutoComplete component which can be found here. Below is my code snippet: <Autocomplete open={showUniSuggs} onOpen={this.props.getUniversityOptions} onChange={(event, value) => this.props.handleUniversi ...

Utilizing Jquery to Pass an Optional Function to Another Function

I am currently working on a function that utilizes AJAX to submit data and then displays a dialog indicating whether the process was successful or not. Everything seems to be functioning smoothly, but I now want to add the capability of passing an addition ...

react-widgets: deciding on the return value for the onSearch function in Multiselect

I'm currently experimenting with react-widgets and utilizing the onSearch function in conjunction with the Multiselect component. Even though I can see that onSearch is being called with the searchTerm, I am unable to incorporate the response into the ...

development session not persisting on local server (localhost:4200)

Currently, I am utilizing angular for the frontend and node.js along with express for the backend of my application. The interesting observation is that when I run the app on localhost:3000 (the designated port for the express app), everything operates cor ...

Exploring TypeORM: Leveraging the In() function within @ManyToMany relationships

There are two main characters in my story: Hero and Villain (their profiles are provided below). How can I utilize the Encounter() method to identify all instances where the Hero interacts with the Villain based on an array of Villain IDs? I am seeking a ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

Differentiating categories in the second parameter for controller method in AngularJS?

As a newcomer to Angular, I have noticed that the locals argument in the controller function can sometimes be just a function and other times an array. angular.module('contentful').controller( 'FormWidgetsController', ['$s ...

Node.js: Handling Undefined Request Parameters

My get route is set up to receive two parameters "limit" and "page". router.get('/:limit/:page', userController.list); class UserController{ public list(req:Request, res:Response): void{ const limit:number = +req.params.limit || 25; ...

Challenge involving CSS and Javascript for solving puzzles

In my attempt to create a puzzle with 2 rows and 3 columns using CSS and JavaScript, I envision the pieces of the puzzle being black and cut into various shapes. The objective is for users to drag these pieces onto the board in order to complete it. I have ...