How to produce JSON in the format that Flot expects?

1

Doubt on how to serialize to return this JSON.

I'm using the Flot library ( link ) to present a chart. I can generate the graphics.

In my view I'm using it like this:

$.ajax({
            url: '/graficos/GeraTesteFlot',
            method: 'GET',
            dataType: 'json',
            success: function (retorno) {
                $.plot($("#divFlot"), [retorno], options);                
            }
        });

But I'm having trouble generating JSON in the correct format. I need a JSON like this:

  [
      { label: "José", data: [[1, 2], [2, 5]] }, 
      { label: "Maria", data: [[1, 5], [2, 3]] }
  ]

And I try to generate it with the code below:

    public JsonResult GeraTesteFlot()
    {
        // Exemplo de retorno desejado : 
        // É um array de series, e cada série tem uma label e um array de "data"
        //
        // Ex:
        //  [
        //      { label: "José", data: [[1, 2], [2, 5]] }, 
        //      { label: "Maria", data: [[1, 5], [2, 3]] }
        //  ];

        List<object> series = new List<object>();
        series.Add(new
        {
            label = "José",
            data = new[] { new double[] { 1, 2}, new double[] { 2, 5} }
        });

        series.Add(new
        {
            label = "Maria",
            data = new[] { new double[] { 1, 5}, new double[] { 2, 3} }
        });

        return Json(series, JsonRequestBehavior.AllowGet);
    }

But this code returns me the JSON like this:

  [
      { "label": "José", "data": [[1, 2], [2, 5]] }, 
      { "label": "Maria", "data": [[1, 5], [2, 3]] }
  ]

The problem is "" double quotes in the attribute name. Instead of "label": "José" , I need label: "José" without "" no label .

How to do it?

    
asked by anonymous 17.07.2014 / 21:28

2 answers

2

As Wakim commented, the generated format was already correct. What I had wrong was in the Ajax call.

The correct call should be

$.ajax({
            url: '/graficos/GeraTesteFlot',
            method: 'GET',
            dataType: 'json',
            success: function (retorno) {
                $.plot($("#divFlot"), retorno, options);                
            }
        });

That is, where was $.plot($("#divFlot"), [retorno], options); correct is $.plot($("#divFlot"), retorno, options);

After this correction, the graph generated normally.

    
17.07.2014 / 22:04
1

When setting your data , be sure to pass the Controller return within the JSON.parse() JavaScript method:

...
data: JSON.parse(retorno),
...
    
17.07.2014 / 21:40