将json字符串值转换为数字

我有一个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中的值是数字而不是字符串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); } }); }); 

像这样的东西(其中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 } ] 

试试这个。 我没有测试它但应该工作。

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

试试这个

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

直播

您无需检查值是否为数字:

 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("
" + JSON.stringify(jsonForChart, null, 3) + "

");