1

Very new to both JSON and jQuery, but here is what I am trying to do - I am returning a JSON string to my webpage as part of a bigger report model in order to create a number of graphs (using jqPlot) at the same time the report is generated.

To practice with these charts, I was using the following tutorial - Tutorial

Here is the jQuery from this tutorial -

jQuery(document).ready(function() {
    urlDataJSON = '/Graph/HearthRateDataJSON';

    $.getJSON(urlDataJSON, "", function(data) {
        var dataLines = [];
        var dataLabels = "";
        $.each(data, function(entryindex, entry) {
            dataLines.push(entry['Serie']);
            dataLabels = dataLabels + entry['Name'];
        });

        Plot(dataLines, dataLabels);
    });
});

function Plot(dataLines, dataLabels) {
    var line1 = "{ label: 'line1.0' }";
    options = {
        legend: { show: true },
        title: 'Heart rate overview',
        axesDefaults: { pad: 1 },
        seriesDefaults: { showMarker: false, trendline: { show: false }, lineWidth: 3 },
        axes: {
            yaxis: { min: 0, autoscale: true, label: 'HR[bpm]', labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
            xaxis: { autoscale: true, label: 'Time', labelRenderer: $.jqplot.CanvasAxisLabelRenderer }
        }
    };

    //Data from database is already an array!
    plot = $.jqplot('chartdiv', dataLines, options);

    plot.redraw(); // gets rid of previous axis tick markers
}

To retrieve the JSON data, this tutorial uses the getJson() method to point to a link. I have the JSON string ready to pass through to the jQuery however, e.g.

[
    {"Name":"Patient","Serie":[[1,4],[2,25],[3,7],[4,14],[5,13]]},
    {"Name":"Test","Serie":[[1,13],[2,5],[3,7],[4,20],[5,17]]}
]

In the jqPlot examples, they pass hardcoded data through as follows:

$(document).ready(function(){
  var plot1 = $.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]);
});

However, my automatically generated JSON string has the curly braces, etc. Is there a way to pass this through to jQuery without using the getJson method?

EDIT-Pie Chart Jquery Code

    $(document).ready(function () {
        var data4 = '[{ "Label": "Car", "Value": 9 },{ "Label": "Bus", "Value": 2 },{ "Label": "Train", "Value": 7 },{ "Label": "Plane", "Value": 8 },{ "Label": "Boat", "Value": 4 }]';

        var data = $.parseJSON(data4);

        var plot1 = jQuery.jqplot('pieChart', [data],
    {
        seriesDefaults: {
            // Make this a pie chart.
            renderer: jQuery.jqplot.PieRenderer,
            rendererOptions: {
                // Put data labels on the pie slices.
                // By default, labels show the percentage of the slice.
                showDataLabels: true
            }
        },
        legend: { show: true, location: 'e' }
    }
  );
    });
2
  • You can parse (without the GET request) using $.parseJSON: api.jquery.com/jQuery.parseJSON Commented May 10, 2012 at 15:12
  • What exactly are you looking for, another $.ajax shortcut, using $.ajax, using XMLhttpRequest, or not using Ajax at all and just parsing a string or something else entirely ? Commented May 10, 2012 at 15:13

3 Answers 3

3

use parseJSON:

 var plotline =  $.parseJSON(jsonstring);

this will work like getJSON, only instead of getting a url, you can pass on your string.

http://api.jquery.com/jQuery.parseJSON/

Sign up to request clarification or add additional context in comments.

2 Comments

@Rodik...this seems to be exactly what I need. I have tried it however and my graph is not displaying :S Is there any way to see the output of the parsed json string?
use a console enabled browser, and use console.log(plotline);
2

You could parse it with any suggested methods provided in other answers and then using it. Or just simply use the JSON data you have as it is an array and all in {} treat as maps. Therefore, you can use them straight without any parsing as I do in a similar situation shown in the code available here.

In the sample provided there is JSON data encoded in variable called json.

var json = [{
    "Name": "Poll Results",
    "Serie": [[2, 5, 4], [4, 1, 7], [6, 3, 1], [3, 4, 2]]}];
var dataLines = json[0].Serie;
var title = json[0].Name;

Then at the end dataLines variable is passed to the chart.

EDIT

After playing with the sample you provided I came to the following conclusions. Apparently the given data is not a format of JSON that the parseJSON method of jQuery can work with. But when you stringify it works.

My sample showing it works fine after application of stringify on the data.

I tried and turned your JSON into a its String equivalent by wrapping it inside '' and it worked. So the answer is simple to use parseJSON method you must pass it a String and not an Object of any other sort.

4 Comments

thanks for the suggestion. I think I'd rather go ahead with parsing the Json, as I almost have this working. The chart generates but looks like there is no data for it. I tested the parse method here - jsfiddle.net/3cbVW ..as you can see it is returning null. Is there something I am doing wrong with it?
I have also included the Jquery for the pie chart I am trying to generate, if it's of any interest.
Please check out my EDIT. Therefore, think again if it is worth to parse the object again? :)
Oh god, ha. I think I'll leave the parsing alone...Thanks for the help! :)
2

You can also use browser's native JSON.parse method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.