skip to Main Content

How can I convert data types to number using JSON.parse and Reviver function? Have tried some options and examples but not sure what I’m doing wrong here. Background is that I’m using Typescript interface which has defined types but incoming Json file has "" for all values.

I only need to apply transformation from String to Number, no other cases exist.

JSON input example ->

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

Expected output

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

I have tried following snippet to make it happen:

    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;
    });

Or should I just replace current Interface declaration?

2

Answers


  1. Try so:

    JSON.parse(jsonString, (key, value) => {
    
       if (!isNaN(value)) {
          return Number(value);
       }
    
       return value;
    });
    

    Only if the value represent a number then is converted to a number

    Login or Signup to reply.
  2. It doesn’t make sense to JSON.stringify just to JSON.parse it again. Verify this example 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
      }))
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search