Pass Json string to JQuery NOT using getJson()

纵饮孤独 提交于 2019-12-08 06:51:08

问题


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' }
    }
  );
    });

回答1:


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.




回答2:


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/




回答3:


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



来源:https://stackoverflow.com/questions/10537000/pass-json-string-to-jquery-not-using-getjson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!