olivier
olivier

Reputation: 2645

Convert all the string values to int from JSON response

Sorry for this beginner question:

I'm getting this as response:

{id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"}

Now i would like to convert rank: "1", price_usd: "15487.0" to rank: 1, price_usd: 15487.0

The reason I need this i because my table sorts alphanumeric instead numeric.

How can I do this?

Upvotes: 2

Views: 83

Answers (3)

Slai
Slai

Reputation: 22876

The JSON.parse reviver can be used to convert or filter values:

j = '{"id":"bitcoin","name":"Bitcoin","symbol":"BTC","rank":"1","price_usd":"15487.0"}'

o = JSON.parse(j, (k, v) => isNaN(+v) ? v : +v)

console.log(o)

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can do it with,

var obj = {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"};

Object.keys(obj).forEach((itm) => {
 if(!Number.isNaN(+obj[itm])) obj[itm] = +obj[itm];
});

console.log(obj);

A simple number conversion is playing the role here. If a non numerical string gets converted into a number by using the + operator, it will return a NaN. By using that we could achieve what you want.

If you want to use a reliable way of checking NaN, then go with the below approach,

var obj = {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"};

Object.keys(obj).forEach((itm) => {
 let conv = +obj[itm];
 if(conv == conv) obj[itm] = +obj[itm];
});

console.log(obj);

This is a reliable approach. Because as per ECMA script, the reliable way to check whether a number is NaN is to check whether the number is equal to itself or not. If it is not equal, then that number is NaN.

Upvotes: 4

Md Adil
Md Adil

Reputation: 307

if you are using mysql as database you can make your column in table rank as int and price_usd as decimal then sort will work correctly.

if you want to convert your data client side. then you can do like this

for(var k in data) {
if(k == 'price_usd') {
 data[k] = parseFloat(data[k]);
  }
// for rank also
 }

Upvotes: 0

Related Questions