Error generating obj with JSON.parse()

Asked

Viewed 93 times

-1

I have the code s following that works well

		var ctx = $( "#myChart" );
		var datasets = 
		[ {
			label: "Gcéu 1",
			data: [ {
				x: "2019/03/01",
				y: 20
			}, {
				x: "2019/03/02",
				y: 10
			}, {
				x: "2019/03/05",
				y: 5
			} ]
		 } , 
		 {
			label: "Gcéu 2",
			data: [ {
				x: "2019/03/01",
				y: 15
			}, {
				x: "2019/03/03",
				y: 10
			}, {
				x: "2019/03/10",
				y: 2
			} ]
		 } , 
		 {
			label: "Gcéu 3",
			data: [ {
				x: "2019/03/07",
				y: 7
			}, {
				x: "2019/03/08",
				y: 8
			}, {
				x: "2019/03/19",
				y: 9
			} ]
		} ];
		
		var scatterChart = new Chart( ctx, {
			type: 'line',
			data: {
				datasets: datasets
			},
			options: {
				title: {
					display: true,
					text: 'Gráfico presenças dos Gcéus'
				},
				scales: {
					yAxes: [ 
					{
						scaleLabel: {
						  display: true,
						  labelString: 'Presenças'
						}
					}],
					xAxes: [ 
					{
						scaleLabel: {
						  display: true,
						  labelString: 'Datas'
						},
						type: 'time',
						time: {
							unit: 'day',
							displayFormats: {
								'day': 'DD/MM/YYYY',
							}
						},
						ticks: {
							source: 'data'
						}
					} ]
				}
			}
		} );
	<canvas id="myChart"></canvas>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/pt-br.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>

But the variable datasets above is static and I intend to pull from the database to generate the graph as below but is giving error:

//dataRelatorio vem do PHP e a saida é como a imagem abaixo um json
  var dataRelatorio = window.dadosRel;
	
	var ctx = $(".line-chart");

	var dados = "[";
	
	for (rel in dataRelatorio) {

		dados += "{ 'label': 'Gcéu " + rel + "', 'data': [";
		
		for (var i = 0; i < Object.keys(dataRelatorio).length; i++) { 

			dados += "{ 'x': '" + dataRelatorio[rel][i]['data'] + "', 'y': " + dataRelatorio[rel][i]['decisoes'] + "},";		

		}
		dados = dados.substring(0, dados.length - 1);
		dados += "]},";	

	};

    dados += "]";
	dados = dados.substring(0, dados.length - 1);
    console.log(dados);
	dados = JSON.parse(dados);
    console.log(dados);
	
	var scatterChart = new Chart( ctx, {
		
		type: 'line',
		data: {
			datasets: [dados]
		},
		options: {
			title: {
				display: true,
				text: 'Gráfico crescimento dos Gcéus'
			},
			scales: {
				yAxes: [ 
				{
					scaleLabel: {
					  display: true,
					  labelString: 'Descisões no período)'
					}
				}],
				xAxes: [ 
				{
					scaleLabel: {
					  display: true,
					  labelString: 'Datas'
					},
					type: 'time',
					time: {
						unit: 'day',
						displayFormats: {
							'day': 'DD/MM/YYYY',
						}
					},
					ticks: {
						source: 'data'
					}
				} ]
			}
		}
	} );	

});
	<canvas class="line-chart"></canvas>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/pt-br.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>

inserir a descrição da imagem aqui

That is the error:

Uncaught Syntaxerror: Unexpected token ' in JSON at position 2 at JSON.parse () At Htmlbuttonelement. (admin.php?reports&acao=celulas:243) At Htmldocument.Dispatch (jquery-2.1.4.min.js:3) At Htmldocument.r.Handle (jquery-2.1.4.min. js:3)

How to correct?

ADD:

Generating the array PHP to send to $.ajax:

$relatorioGr[$celulasReuniao->getIdCelula()][$i]["data"] = $celulasReuniao->getData();
$relatorioGr[$celulasReuniao->getIdCelula()][$i]["ofetas"] = $celulasReuniao->getOferta();
$relatorioGr[$celulasReuniao->getIdCelula()][$i]["decisoes"] = $celulasReuniao->getDecisoes();

Ajax:

$.ajax({
    url: "_scripts/_php/_buscas/relatorioCelulas.php",
    type: "POST",
    dataType: "json",
    data: {dados},
    success: function (result) {
        window.dadosRel = result.data;              
    }
});
  • Javascript does not allow line breaks in strings as you have in the question. And this JSON is an Array, but it is missing [ ] at the beginning and end of the string. Where this string comes from?

  • ah Sm, I put break line just to be legible but the code is not like this, see the additional I put in the question. You’ve reached https://repl.it/@Carlosrocha1/Bewitchedboilingbase?

  • This link is missing [] around the JSON. You don’t need the line JSON.parse(dados); and lack value for the first y...

  • I changed the question

  • You can place the lines of code where you receive the JSON from the server?

  • receive a js array. Added at the end of the question

  • In that case window.dadosRel is already an object/array, you should not use the JSON.parse().

Show 2 more comments

1 answer

0

First: your keys and values(string) have to be in double quotes. Second: You are using two root elements.

Try it on there:

{"data_1":{ 
  "label": "Gcéu 17", 
  "data": 
       [
         { 
            "x": "2019-03-01", 
            "y": 6
         },
         { 
            "x": "2019-03-03", 
            "y": 3
        }
       ]
},
"data_2":{ 
  "label": "Gcéu 18", 
  "data": 
       [
         {
             "x": "2019-03-02", 
             "y": 0
         },
         { 
             "x": "2019-03-05", 
             "y": 1
         }
       ]
}
}
  • I tried to make it said but it didn’t work out. I put in question my attempt, See where I went wrong doing favor? It needs to be that way because it is to colcoar in the Line Chart Chart

  • I changed the question

Browser other questions tagged

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