简体   繁体   English

将JSON数据解析为C3.js图表​​的数组

[英]Parsing JSON data into an array for a C3.js chart

I'm sending a json variable from django to C3.js in this format: 我正在以这种格式从django向C3.js发送一个json变量:

{
   datetime.date(2015, 5, 1): 22792461.479999978, 
   datetime.date(2015, 6, 1): 24807797.38999998, 
   datetime.date(2015, 7, 1): 25261456.609999962
}

I need to extract the values and compile them into an array ready for use by c3.js. 我需要提取值并将其编译为准备供c3.js使用的数组。 Here's my script: 这是我的脚本:

<script>
   {% include "croydon_dashboards/dashboard_includes/gb_locale.html" %}

   var row_value = {{ row_value }};
   var sum_list = [];

   for(var i in row_value)
      sum_list.push(row_value[i])

   sum_list = JSON.stringify(sum_list);

   var chart = c3.generate({
       data: {
          columns: [
              sum_list
          ],
          type: 'bar'
       },
        bar: {
           width: {
              ratio: 0.5
           }
       }
   });
</script>

Hard coding values into the chart works, so I know the c3.js is right, but there's something wrong with the way I'm building the array. 硬编码值到图表中是可行的,所以我知道c3.js是正确的,但是我构建数组的方式出了点问题。

I know that there's an answer here: JSON Data doesn't show on c3.js bar chart 我知道这里有一个答案: JSON数据未显示在c3.js条形图上

but I'm new to javascript and can't work out how to parse the json that I'm working with. 但我是javascript新手,无法解决如何解析正在使用的json的问题。

You do not need to JSON.stringify() your data to use it with c3. 您无需将数据JSON.stringify()即可与c3一起使用。
But you may have to JSON.parse() it to make it look like this: 但是您可能需要JSON.parse()使其看起来像这样:

var row_value = {
   "2015-05-01": 22792461.479999978, 
   "2015-06-01": 24807797.38999998, 
   "2015-07-01": 25261456.609999962
};

And don't forget to add text label at the beginning of data array: 并且不要忘记在数据数组的开头添加文本标签:

// This first value of array if the name of your data
 var sum_list = ['something'];

The rest of your code works. 您的其余代码工作正常。

 for(var i in row_value)
    sum_list.push(row_value[i])


 var chart = c3.generate({
     data: {
        columns: [
            sum_list
        ],
        type: 'bar'
     },
      bar: {
         width: {
            ratio: 0.5
         }
     }
 });

See this fiddle . 看到这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM