Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing JSON in amcharts - How to modify a JSON output (Ruby on Rails)
    text
    copied!<p>I am trying to use <a href="http://www.amcharts.com/" rel="nofollow">amcharts</a> and I want to use JSON to format the data for my chart. However, it seems that the syntax that amcharts accepts is not valid JSON. </p> <p>Here is the javascript code for the data for a hardcoded amchart chart:</p> <pre><code> var chartData = [{ country: "Czech Republic", litres: 301.90 }]; </code></pre> <p>Here is the code if I want to create the same chart with embedded ruby:</p> <p>Controller</p> <pre><code> @chart_data = [{"country": "Czech Republic", "litres": 301.90}] </code></pre> <p>View</p> <pre><code> var chartData = &lt;%= @chart_data.to_json %&gt;; </code></pre> <p>The <a href="http://jsonlint.com/" rel="nofollow">valid JSON</a> output:</p> <pre><code> [{"country": "Czech Republic", "litres": 301.90}] </code></pre> <p>However, what amcharts accepts is:</p> <pre><code> [{country: "Czech Republic", litres: 301.90}] </code></pre> <p>Therefore my chart is not working because amcharts doesn't accept the valid JSON. So is there a way to create "invalid" JSON without the double quotes around country and litres? Or is there a better way to get the data in the form amcharts accepts? Any help would be greatly appreciated.</p> <p>Here is the full javascript:</p> <pre><code> &lt;script type="text/javascript"&gt; var chart; var legend; var chartData = [{ country: "Czech Republic", litres: 301.90 }, { country: "Ireland", litres: 201.10 }, { country: "Germany", litres: 165.80 }, { country: "Australia", litres: 139.90 }, { country: "Austria", litres: 128.30 }, { country: "UK", litres: 99.00 }, { country: "Belgium", litres: 60.00 }]; AmCharts.ready(function () { // PIE CHART chart = new AmCharts.AmPieChart(); chart.dataProvider = chartData; chart.titleField = "country"; chart.valueField = "litres"; chart.outlineColor = "#FFFFFF"; chart.outlineAlpha = 0.8; chart.outlineThickness = 2; // WRITE chart.write("chartdiv"); }); &lt;/script&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload