Manipulate and model Json object

Asked

Viewed 2,664 times

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 complete code is here: JS Fiddle

Must look something like this, is 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
 }
} );
  • Do you want to convert the first object (an array, actually) into the second? Where do the values of the second object come from (i.e., milestone, color, Descricao, etc..)?

  • The color preferably I wanted it to alternate in 3 different colors (to give a highlight). The Milestone I will have to do a JOIN (to get the description of the Milestone I have the Milestone ). o Description is the same value as Description of the first array.

  • Put more information in your question (for example, the "table" of the Stones, which means Early / Early Start, etc.). Without this it is impossible to know how to transform the first JSON into the second...

  • Updated question.

  • 1

    Look, it’s hard to manipulate a json as a "string", so create a var dataprovider as an object var dataprovider = { milestone: "", atividade: [] }, so you can throw the value of the received object directly into the dataprovider object, thus dataprovider.milestone = val.CodigoMilestone, and to add items in the activity array, thus: dataprovider.atividade.push( { InicioCedo: val.InicioCedo, color: "#7B742C" } ). And at the end, you turn this object into a Json string, like this: var strJson = JSON.stringify( dataprovider )

2 answers

5

First of all you need the names of Milestones, as already pointed out in comment. I will assume that you have a type object:

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

When you receive JSON, the first thing you need to do (assuming you’ve already converted it from text to a Javascript object) is to separate the activities by Milestones. For every Milestone will be an object in the dataProvider, which in turn will have a list of activities that apply to it. Let’s start 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 didn’t understand very well the logic of its fields that represent date, but as the X axis of your graph goes from 0 to 30, I imagined that it represents the day of the month (if it is, it was to go until 31, no?):

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 the dataProvider. As already pointed out in comment, to do this by manipulating strings is unnecessary, laborious, subject to errors and with worse performance. I suggest doing manipulating normal objects (even because the 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": {},
...

Complete example in jsFiddle.

0

Use the function push() to add elements in 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.