1

I am trying to render jqplot widget with dynamic JSON and I cannot find how to do it.

The Only examples I saw included reading JSON from file but I want to use JSON as String for example:

{"oranges":"10","apples":"20","bananas":"6"}

any idea?

zohar
  • 2,298
  • 13
  • 45
  • 75

2 Answers2

3

The data in your question is not a string, it's a javascript object literal.

If you have oranges, apples and bananas you'll probably want to draw a bar chart; you'll need to extract the labels and the values from the object and then plot the chart:

var chart_data = {"oranges":"10", "apples":"20", "bananas":"6"};
var line1 = [];
for (var prop_name in chart_data) {
    line1.push([prop_name, chart_data[prop_name]])
}
// line1 should be [["oranges", 10], ["apples", 20], ["bananas", 6]]


// code snippet from http://www.jqplot.com/tests/rotated-tick-labels.php
// please change it as you need
var plot1 = $.jqplot('chart1', [line1], {
    title: 'Fruits',
    series: [{renderer:$.jqplot.BarRenderer}],
    axesDefaults: {
        tickRenderer: $.jqplot.CanvasAxisTickRenderer 
    },
    axes: {
      xaxis: {
        renderer: $.jqplot.CategoryAxisRenderer
      }
    }
});
Toni Toni Chopper
  • 1,833
  • 2
  • 20
  • 29
  • it is not working. can you please edit the question with the full page/html code? – zohar Dec 11 '12 at 11:48
  • What is not working? I'm pretty sure `line1` is correct, with that you should be able to render the chart (the second part is a snippet I've copied from the jqPlot website, please amend it as necessary) – Toni Toni Chopper Dec 11 '12 at 11:52
  • Could you create a jsFiddle with the HTML and javascript? It would be easier to debug. – Toni Toni Chopper Dec 11 '12 at 15:01
  • 1
    [Here](http://jsfiddle.net/HzvyB/2/) you go. Please note how jqPlot .css and .js files are specified in `Manage Resources (6)` on the left – Toni Toni Chopper Dec 11 '12 at 16:19
0
$.getJSON(url,"json").success(function(data) {
var line1 = [];
var content = $.parseJSON( data);
$.each(content, function(index, item) {
        line1.push([item.date, item.value])
});

var plot1 = $.jqplot("chart1",[line1], { .....

This is a good exemple how to convert json data to array who jqplot can use ...

chakroun yesser
  • 1,407
  • 1
  • 12
  • 18