Convert json string value to number

后端 未结 4 1314
孤城傲影
孤城傲影 2021-01-03 03:24

I have a JSON string that reads:

[{
    \"id\": \"id2\",
    \"index\": \"2\",
    \"str\": \"str2\",
    \"cent\": \"200\",
    \"triplet\": \"222\"
},
{
           


        
4条回答
  •  滥情空心
    2021-01-03 03:40

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

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

提交回复
热议问题