将JSON字符串值转换为数字

6
我有一个JSON字符串,如下所示:

[{
    "id": "id2",
    "index": "2",
    "str": "str2",
    "cent": "200",
    "triplet": "222"
},
{
    "id": "id3",
    "index": "3",
    "str": "str3",
    "cent": "300",
    "triplet": "333"
},
{
    "id": "id4",
    "index": "4",
    "str": "str4",
    "cent": "400",
    "triplet": "444"
},
{
    "id": "id5",
    "index": "5",
    "str": "str5",
    "cent": "500",
    "triplet": "555"
}]

键值对是动态从服务器获取的,我事先不知道要期望什么数据。对于我使用的绘图库,需要JSON中的值是数字而不是字符串,例如"index":2而不是"index":"2"。我需要在客户端使用纯JS或jQuery进行此操作。
这是我的方法,但似乎无效:
var temp = //some json that I receive
var jsonForChart = jQuery.extend(true, {}, temp);
$.each(temp, function(key, value) {
    $.each(value, function(k, v) {
        if(!isNaN(v)){
            jsonForChart[key][k] = Number(v);
        }
    });
});

有什么问题吗?你是否收到任何错误信息? - Tjaart van der Walt
4个回答

12

类似这样的东西(其中objects是一个对象数组):

JavaScript

for(var i = 0; i < objects.length; i++){
    var obj = objects[i];
    for(var prop in obj){
        if(obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])){
            obj[prop] = +obj[prop];   
        }
    }
}

console.log(JSON.stringify(objects, null, 2));
最后一行将会打印输出这个:
[
  {
    "id": "id2",
    "index": 2,
    "str": "str2",
    "cent": 200,
    "triplet": 222
  },
  {
    "id": "id3",
    "index": 3,
    "str": "str3",
    "cent": 300,
    "triplet": 333
  },
  {
    "id": "id4",
    "index": 4,
    "str": "str4",
    "cent": 400,
    "triplet": 444
  },
  {
    "id": "id5",
    "index": 5,
    "str": "str5",
    "cent": 500,
    "triplet": 555
  }
]

2
这将null转换为0。我刚刚因此花了2个小时解决一个错误。 - Mickael Bergeron Néron
2
@MickaelBergeronNéron 已修复。 - Arg0n
是的,这个可以工作。但是它能再深入一点吗?如果其中一个属性是对象,那么这段代码甚至应该进入该对象并转换其值。有点像递归。 - pramodpxi

2

您不需要检查值是否为数字:

var temp = [{
  "id": "id2",
  "index": "2",
  "str": "str2",
  "cent": "200",
  "triplet": "222"
}, {
  "id": "id3",
  "index": "3",
  "str": "str3",
  "cent": "300",
  "triplet": "333"
}, {
  "id": "id4",
  "index": "4",
  "str": "str4",
  "cent": "400",
  "triplet": "444"
}, {
  "id": "id5",
  "index": "5",
  "str": "str5",
  "cent": "500",
  "triplet": "555"
}];

var jsonForChart = jQuery.extend(true, {}, temp);
$.each(temp, function(key, value) {
  $.each(value, function(k, v) {
    // if the value can be parsed to int, it will be OR the value remains untouched
    jsonForChart[key][k] = +v || jsonForChart[key][k];
  });
});

document.write("<pre>" + JSON.stringify(jsonForChart, null, 3) + "</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你会得到一个大对象,但这是你在看到这行代码 var jsonForChart = jQuery.extend(true, {}, temp); 时所期望的。


1
尝试一下。我还没有测试过,但应该可以工作。
var temp = //some json that I receive
var jsonForChart = jQuery.extend(true, {}, temp);
$.each(temp, function(key, value) {
    $.each(value, function(k, v) {
        if(!isNaN(parseInt(v))){
            jsonForChart[key][k] = parseInt(v);
        }else{
            jsonForChart[key][k] = v;
        }
    });
});

这个else条件并没有太大的区别。不过还是谢谢你的建议 :) - Slartibartfast

1

试试这个

// Iterate thorugh the array
[].forEach.call(x, function(inst, i){
    // Iterate through all the keys
    [].forEach.call(Object.keys(inst), function(y){
        // Check if string is Numerical string
        if(!isNaN(x[i][y]))
            //Convert to numerical value
            x[i][y] = +x[i][y];
    });

});

console.log(x);

Live FIddle

可以翻译为:

{{链接1:现场小提琴}}


转换方面工作正常;但以某种方式并没有得到所期望的图表结果。 - Slartibartfast

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接