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
Try so:
Only if the value represent a number then is converted to a number
It doesn’t make sense to
JSON.stringify
just toJSON.parse
it again. Verify this example on typescript playground –