如何使用Javascript将一些json元素转换为Number

时间:2016-10-06 14:38:21

标签: javascript json

我通过以下方式获得jsondata:

 [
{"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":....}]

下面的代码解析了所有元素并将每个Numeric值转换为Number,但我不想将CL_ORD_ID转换为Number,如何修改下面的代码?

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

2 个答案:

答案 0 :(得分:0)

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

虽然更好的答案是在转换过程中添加要跳过的动态键列表:

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

答案 1 :(得分:0)

如果只是CL_ORD_ID你不想转换,你可以尝试:

var value = obj[key];
memo[key] = isNumeric(value) && key !== "CL_ORD_ID" ? Number(value) : value;
return memo;

或者你不能将它们转换为数字,而是将你想要成为数字的值转换为数字,当你需要它们作为数字时。