从json对象中解析和删除引号

时间:2013-12-09 21:09:52

标签: json jchartfx

我的数据

var data = [
{"title":"2013-12-09", "calls_in":"345", "calls_out":"100"},
{"title":"2013-12-08", "calls_in":"125", "calls_out":"97"}, 
{"title":"2013-12-07", "calls_in":"85", "calls_out":"2"},
{"title":"2013-12-06", "calls_in":"185", "calls_out":"22"},
{"title":"2013-12-05", "calls_in":"74", "calls_out":"419"}
]

如上所述以json格式从PHP脚本到达。我正在使用一个API,即'jChartFX',它基本上是一个javascript图形库,可以使用javascript / jquery动态制作酷图表。

目前使用库上方的数据无法解析它。由于整数值周围的引号,它失败了。我需要采用以下格式的数据:

var data = [
        {"title":"2013-12-09", "calls_in":345, "calls_out":100},
        {"title":"2013-12-08", "calls_in":125, "calls_out":97}, 
        {"title":"2013-12-07", "calls_in":85, "calls_out":2},
        {"title":"2013-12-06", "calls_in":185, "calls_out":22},
        {"title":"2013-12-05", "calls_in":74, "calls_out":419}
    ]

你看,整数没有用引号括起来。我怎么能用jQuery或javascript做到这一点。

在最基本的形式(工作)中,完整的脚本看起来类似于:

<!DOCTYPE html>
<html>
<head>
 <link rel="stylesheet" type="text/css" href="chartfx.css" />
 <script type="text/javascript" src="js/jchartfx.system.js"></script>
 <script type="text/javascript" src="js/jchartfx.coreBasic.js"></script>  
</head>
<body onload="loadChart()">
<div id="ChartDiv" style="width:600px;height:400px"></div>
<script>

var chart1;

function loadChart(){        

    chart1 = new cfx.Chart();
    chart1.getData().setSeries(2);
    chart1.getAxisY().setMin(0);
    chart1.getAxisY().setMax(700);

    var series1 = chart1.getSeries().getItem(0);
    var series2 = chart1.getSeries().getItem(1);

    series1.setGallery(cfx.Gallery.Lines);
    series2.setGallery(cfx.Gallery.Lines);

    var data = [
        {"title":"2013-12-09", "calls_in":345, "calls_out":100},
        {"title":"2013-12-08", "calls_in":125, "calls_out":97}, 
        {"title":"2013-12-07", "calls_in":85, "calls_out":2},
        {"title":"2013-12-06", "calls_in":185, "calls_out":22},
        {"title":"2013-12-05", "calls_in":74, "calls_out":419}
    ]

    console.log(data);
        chart1.setDataSource(data);
        var divHolder = document.getElementById('ChartDiv');
    chart1.create(divHolder);            

  }

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

选项1:在将数据传递给jChartFX之前,只需在每个整数值的JavaScript中调用parseInt()

选项2:如果您可以修改PHP脚本,请对您的JSON进行编码,如下所示:json_encode($arrayContainingTheData, JSON_NUMERIC_CHECK );

选项2的示例:

$x = array( 'foo' => "1", 'bar' => "2");
echo json_encode($x, JSON_NUMERIC_CHECK  );

结果:{"foo":1,"bar":2}

更多信息: