Angad Angad - 2 months ago 7
JSON Question

How to not convert some json elements to Number using Javascript

I have jsondata in the following way:

[
{"WEIGHTED_ARR_LAST_SLP":"0.03801186624130076","SLIPPAGE_INTERVAL_VWAP_BPS":"10.2711","ROOT_ORDER_ID":"735422197553491","ARRIVAL_MID_PX":"93.6100","WEIGHTED_ARR_SLP":"0.12323190317127024","AVG_PX":"93.6586","LEAVES_QTY":"0","WEIGHT":"0.02372627566400397","PARTICIPATION_RATE":"0E-12","LOCAL_REF_END_TIME":"2016-09-06 06:00:27.775","WEIGHTED_IVWAP_SLP":"0.2436949499725512","NOTIONAL_USD":"477940","LIQ_CONSUMPTION":"15.21","EXEC_QTY":"5103","CL_ORD_ID":"7245294057012908344","LOCAL_REF_START_TIME":"2016-09-06 05:59:57.844","SLIPPAGE_END_LAST_ARR_LAST_BPS":"1.6021","IVWAP_PX":"93.5625","LIMIT_PX":"93.6100","ORDER_ID":"735422197553491","SLIPPAGE_ARR_MID_BPS":"5.1939","ORDER_QTY":"5103","EXECUTION_STYLE":"2"},{"WEIGHTED_ARR_LAST_SLP":....}]


The below code is parsing through all the elements and converting each Numeric value to Number, but I don't want to convert CL_ORD_ID to Number, how do I modify the below code for that??

var json = JSON.parse(jsondata);

function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

var parsedData = json.map(function(obj) {
return Object.keys(obj).reduce(function(memo, key) {
var value = obj[key];
memo[key] = isNumeric(value) ? Number(value) : value;
return memo;
}, {})
});

console.log(parsedData);

Answer
var parsedData = json.map(function(obj) {
    return Object.keys(obj).reduce(function(memo, key) {
        var value = obj[key];
        if(key == 'CL_ORD_ID')
            memo[key] = value;
        else
            memo[key] = isNumeric(value) ? Number(value) : value;
        return memo;
    }, {})
});

Although a better answer would be to add a dynamic list of keys to skip during conversion:

var skip = ['CL_ORD_ID', ... ]

...

var parsedData = json.map(function(obj) {
    return Object.keys(obj).reduce(function(memo, key) {
        var value = obj[key];
        if(skip.indexOf(skip) < 0)
            memo[key] = value;
        else
            memo[key] = isNumeric(value) ? Number(value) : value;
        return memo;
    }, {})
});