将json字符串值转换为数字

Sla*_*ast 3 javascript jquery

我有一个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"
}]
Run Code Online (Sandbox Code Playgroud)

键值对来自服务器,我不会事先知道预期的数据.对于我使用的图表库,我需要JSON中的值是数字而不是字符串viz."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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Arg*_*g0n 6

这样的东西(哪里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));
Run Code Online (Sandbox Code Playgroud)

最后一行将打印出来:

[
  {
    "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
  }
]
Run Code Online (Sandbox Code Playgroud)

  • 这会将 null 转换为 0。我刚刚花了 2 个小时来解决由此引起的错误。 (2认同)
  • @MickaelBergeronNéron 已修复。 (2认同)