javascript 将json字符串值转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34014342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:07:25  来源:igfitidea点击:

Convert json string value to number

javascriptjquery

提问by Slartibartfast

I have a JSON string that reads:

我有一个 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"
}]

The key-value pairs come dynamically from the server and I won't know beforehand what data to expect. For a charting library that I use, I need the values in JSON to be numeric rather than string viz. "index":2instead of "index":"2"I am required to do this manipulation client-side using pure JS or jQuery.

键值对动态地来自服务器,我事先不知道期望什么数据。对于我使用的图表库,我需要 JSON 中的值是数字而不是字符串即。"index":2而不是"index":"2"我需要使用纯 JS 或 jQuery 在客户端执行此操作。

This was my approach but it doesn't seem to work:

这是我的方法,但似乎不起作用:

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

回答by Arg0n

Something like this(where objectsis an Array of objects):

这样的东西(objects对象数组在哪里):

JavaScript

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

The last line will print out this:

最后一行将打印出来:

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

回答by Shanoor

You don't need to check if the value is a number:

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

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>

You get one big object but it's what you expect seeing the line var jsonForChart = jQuery.extend(true, {}, temp);.

你得到一个大物体,但它是你期望看到的线var jsonForChart = jQuery.extend(true, {}, temp);

回答by Harry Bomrah

Try this. I haven't tested it but should work.

试试这个。我还没有测试过,但应该可以工作。

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

回答by void

Try this

试试这个

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

现场小提琴