Handle and model Json object

5

I have a JSON object with the following structure:

[{
        "Codigo": 7,
            "Descricao": "Atividade 1",
            "CodigoMilestone": 6,
            "TempoRevisado": 2,
            "Inicio": "\/Date(1445738400000)\/",
            "InicioCedo": "\/Date(1445738400000)\/",
            "InicioTarde": "\/Date(-62135589600000)\/",
            "TerminoCedo": "\/Date(1445911200000)\/",
            "TerminoTarde": "\/Date(-62135589600000)\/",
            "Ativo": true,
            "Milestone": null,
            "Dependencia": [],
            "Dependencia1": []
    }, {
        "Codigo": 8,
            "Descricao": "Ativade 2",
            "CodigoMilestone": 6,
            "TempoRevisado": 2,
            "Inicio": "\/Date(1445997600000)\/",
            "InicioCedo": "\/Date(1445997600000)\/",
            "InicioTarde": "\/Date(1445911200000)\/",
            "TerminoCedo": "\/Date(1446084000000)\/",
            "TerminoTarde": "\/Date(1446084000000)\/",
            "Ativo": true,
            "Milestone": null,
            "Dependencia": [],
            "Dependencia1": []
    }]

I need to model so that the code below receives the values of this object:

"dataProvider": [ {
    "milestone": "Infraestrutura",
    "atividade": [ {
        "InicioCedo": 1,
        "TempoRevisado": 2,
        "color": "#7B742C",
        "Descricao": "Instalar Banco de Dados"
    }, {
        "InicioCedo": 3,
        "TempoRevisado": 2,
        "color": "#7E585F",
        "Descricao": "Instalar Visual Studio"
    }]
} ],

The full code is here: JS Fiddle

It should look something like this, it's that I do not master Javascript

var atividades =
[{
    "Codigo":7,
    "Descricao":"Atividade 1", 
    "CodigoMilestone":6,
    "TempoRevisado":2, 
    "Inicio":"\/Date(1445738400000)\/",                
    "InicioCedo":"\/Date(1445738400000)\/", 
    "InicioTarde":"\/Date(-62135589600000)\/",         
    "TerminoCedo":"\/Date(1445911200000)\/",
    "TerminoTarde":"\/Date(-62135589600000)\/",
    "Ativo":true, 
    "Milestone":null, 
    "Dependencia":[],
    "Dependencia1":[]
}]

if (atividades != null) {
var dataprovider = '';    
 $.each(atividades, function (key, val) {
    dataprovider += '"dataProvider": [ {'
    '"milestone":' + val.CodigoMilestone,
    '"atividade": [ {'
        '"InicioCedo":' + val.InicioCedo + ',' +
        '"TempoRevisado":' + val.TempoRevisado + ',' +
        '"color": "#7B742C",'
        '"Descricao":' + val.Descricao +
    '}]'
'}],'
})          
}


  AmCharts.useUTC = true;
  var chart = AmCharts.makeChart( "chartdiv", {
  "type": "gantt",
  "theme": "dark",
  "marginRight": 70,
  "period": "bb",
  "dataDateFormat":"DD-MM-YYYY",
  "balloonDateFormat": "JJ:NN",
  "columnWidth": 0.5,
  "valueAxis": {
    "type": "month",
    "minimum": 1,
    "maximum": 30
   },
  "brightnessStep": 10,
  "graph": {
    "fillAlphas": 1,
    "balloonText": "<b>[[Descricao]]</b>: [[open]] [[value]]"
   },
   "rotate": true,
  "categoryField": "milestone",
   "segmentsField": "atividade",
   "colorField": "color",
   "startDate": "01-10-2015",
   "startField": "InicioCedo",
   "endField": "TerminoCedo",
   "durationField": "TempoRevisado",

    **dataprovider** // aqui ficaria a estrutura que está sendo construida no JAVASCRIPT

"chartScrollbar": {},
"chartCursor": {
    "valueBalloonsEnabled": false,
    "cursorAlpha": 0.1,
    "valueLineBalloonEnabled": true,
    "valueLineEnabled": true,
    "fullWidth": true
},
"export": {
    "enabled": true
 }
} );
    
asked by anonymous 30.10.2015 / 20:57

2 answers

6

First of all you need the names of milestones , as already pointed out in comment. I'll assume you have an object type:

var milestones = {
    "6":"Infraestrutura"
}

Upon receiving JSON, the first thing you need to do (assuming you have already converted it to a JavaScript object) is to separate the activities by milestones . For each milestone will be an object in dataProvider , which in turn will have a list of activities that apply to it. Let's start by doing this, without any conversion:

var separacao = { };
function adicionarAtividade(atividade) {
    if ( !separacao[atividade.CodigoMilestone] )
        separacao[atividade.CodigoMilestone] = [];

    separacao[atividade.CodigoMilestone].push(atividade);
}

atividades.forEach(adicionarAtividade);

In addition, it helps to create an auxiliary function to convert an activity from the format that came in JSON to the expected format in dataProvider . I do not quite understand the logic of your fields that represent date, but since the X-axis of your chart goes from 0 to 30, I figured it represents the day of the month (if it was, it was to go to 31, right?):

var cores = ["#7B042C","#7B742C","#7E585F"];
var qualCor = 0;
function converterAtividade(atividade) {
    qualCor = (qualCor+1) % 3; // Alterna entre 3 cores diferentes
    return {
        InicioCedo: converterData(atividade.InicioCedo),
        TempoRevisado: atividade.TempoRevisado,
        color: cores[qualCor],
        Descricao: atividade.Descricao
    };
}

function converterData(data) {
    return new Date(parseInt(data.substring(6, data.length-2), 10)).getDate();
}

Then all you have to do is create dataProvider . As already pointed out in commentary, doing so by manipulating strings is unnecessary, laborious, error prone, and worse performing. I suggest doing normal objects manipulation (even though dataProvider is a normal object, not a JSON):

var dataProvider = [];
for ( var codMilestone in separacao ) {
    var atividades = separacao[codMilestone];
    dataProvider.push({
        milestone: milestones[codMilestone],
        atividade: atividades.map(converterAtividade)
    });
}

Then just use it in creating your chart:

...
"durationField": "TempoRevisado",
"dataProvider": dataProvider,
"chartScrollbar": {},
...

Full example in jsFiddle .

    
03.11.2015 / 05:03
0

Use the push() function to add elements to the array, you can separate it into layers before rendering:

For more information about the chart, see documentation :

AmCharts.useUTC = true;

function convertDate(dateConvert) {
  return  new Date(eval(dateConvert.match(/[0-9]+/gi).join(','))).getDate();
}
function convertDateStart(dateConvert) {
 var data = new Date(eval(dateConvert.match(/[0-9]+/gi).join(',')));
        var day = (data.getDate() < 10) ? data.getDate()+'0' : data.getDate();
        var month= (data.getMonth() < 10) ? data.getMonth()+'0' : data.getMonth();
        var year = data.getFullYear();
    return [day, month, year].join("-");
}

var atividades = [];
var collection = [{
        "Codigo": 7,
            "Descricao": "Atividade 1",
            "CodigoMilestone": 6,
            "TempoRevisado": 2,
            "Inicio": "\/Date(1445738400000)\/",
            "InicioCedo": "\/Date(1445738400000)\/",
            "InicioTarde": "\/Date(-62135589600000)\/",
            "TerminoCedo": "\/Date(1445911200000)\/",
            "TerminoTarde": "\/Date(-62135589600000)\/",
            "Ativo": true,
            "Milestone": null,
            "Dependencia": [],
            "Dependencia1": []
    }, {
        "Codigo": 8,
            "Descricao": "Ativade 2",
            "CodigoMilestone": 6,
            "TempoRevisado": 2,
            "Inicio": "\/Date(1445997600000)\/",
            "InicioCedo": "\/Date(1445997600000)\/",
            "InicioTarde": "\/Date(1445911200000)\/",
            "TerminoCedo": "\/Date(1446084000000)\/",
            "TerminoTarde": "\/Date(1446084000000)\/",
            "Ativo": true,
            "Milestone": null,
            "Dependencia": [],
            "Dependencia1": []
    }, {
        "Codigo": 9,
            "Descricao": "Ativade 3",
            "CodigoMilestone": 6,
            "TempoRevisado": 2,
            "Inicio": "\/Date(1445997600000)\/",
            "InicioCedo": "\/Date(1445997600000)\/",
            "InicioTarde": "\/Date(1445911200000)\/",
            "TerminoCedo": "\/Date(1446084000000)\/",
            "TerminoTarde": "\/Date(1446084000000)\/",
            "Ativo": true,
            "Milestone": null,
            "Dependencia": [],
            "Dependencia1": []
    }];

var dateStart = convertDateStart(collection[0].InicioCedo);

var c = 0;
for (var i in collection) {
    var colors = ["#7B742C","#7E585F",'#CF794A'];
    //primeiro registro
    if (i == 0) {
     atividades.push({
            "InicioCedo": convertDate(collection[i].InicioCedo),
            "TempoRevisado": collection[i].TempoRevisado,
            "color": color,
            "Descricao": collection[i].Descricao
        });
    //ultimo registro
    } else if (i == collection.length - 2) {
          atividades.push({
            "TerminoCedo": convertDate(collection[i].TerminoCedo),
            "TempoRevisado": collection[i].TempoRevisado,
            "color": color,
            "Descricao": collection[i].Descricao
        });
     //demais registros    
    } else {
      atividades.push({
            "TempoRevisado": collection[i].TempoRevisado,
            "color": color,
            "Descricao": collection[i].Descricao
        });
    }
    var color = colors[(c++) % 2];

}

var dataProvider = [{
                    "milestone": "Infraestrutura",
                    "atividades":atividades
                   }];

AmCharts.useUTC = true;
var chart = AmCharts.makeChart( "chartdiv", {
    "type": "gantt",
    "theme": "dark",
    "marginRight": 70,
    "period": "hh",
    "dataDateFormat":"YYYY-MM-DD",
    "balloonDateFormat": "JJ:NN",
    "columnWidth": 0.5,
    "valueAxis": {
        "type": "date",
        "minimum": 7,
        "maximum": 31
    },
    "brightnessStep": 10,
    "graph": {
        "fillAlphas": 1,
        "balloonText": "<b>[[Descricao]]</b>: [[open]] [[value]]"
    },
    "rotate": true,
    "categoryField": "milestone",
    "segmentsField": "atividades",
    "colorField": "color",
    "startDate": dateStart,
    "startField": "InicioCedo",
    "endField": "TerminoCedo",
    "durationField": "TempoRevisado",
    "dataProvider": dataProvider,
    "chartScrollbar": {},
    "chartCursor": {
        "valueBalloonsEnabled": false,
        "cursorAlpha": 0.1,
        "valueLineBalloonEnabled": true,
        "valueLineEnabled": true,
        "fullWidth": true
    },
    "export": {
        "enabled": true
     }
} );

Here it is working

    
06.11.2015 / 18:56