Javascript error: Unexpected string in Parse cloud code - javascript

I'm trying to get info from an httpresponse, parse de JSON and create a new dictionary with an array of dictionaries like :
"data" : {"infracciones": [
{
"folio": "03041487403",
"fecha": "2014-03-16",
"situacion": "Pagada",
"motivo": "POR NO RESPETAR LOS LIMITES DE VELOCIDAD",
},
{
"folio": "0334357403",
"fecha": "2015-04-11",
"situacion": "Pagada",
"motivo": "POR NO RESPETAR LOS LIMITES DE VELOCIDAD",
}],
"tenencia":[ ...]
}
but I'm getting en error : "Unexpected string in main.js:35" but I don't have a clue of what's happening, thanks for your help, here's the code:
Parse.Cloud.httpRequest({
url: url1 ,
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function(httpResponse) {
var json = JSON.parse(httpResponse.data);
var datos = json.infracciones;
var infracciones = [];
var data = {};
var i = 0;
for(i = 0; i < datos.length ; i++){
infracciones[i].["folio"] = datos.folio ; // THIS IS LINE 35
infracciones[i].["fecha"] = datos.fecha ;
infracciones[i].["situacion"] = datos.situacion ;
infracciones[i].["motivo"] = datos.motivo ;
}
data.push({
key : "infracciones",
value : infracciones
});
response.success(data);
console.log(httpResponse.text);
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});

Try this way
var infracciones = [];
var data = [];
var i = 0;
for(i = 0; i < datos.length ; i++){
infracciones[i] = {};
infracciones[i].folio = datos.folio ;
infracciones[i].fecha = datos.fecha ;
infracciones[i].situacion = datos.situacion ;
infracciones[i].motivo = datos.motivo ;
}
data.push({
key : "infracciones",
value : infracciones
});

Related

js errors with Uncaught SyntaxError about argument list

when i write js,i meet with some wrong about SyntaxError,the following is `part of my code
function loadData() {
tree = new dTree('tree');
tree.add(0, -1, '请选择父类')
$.ajax({
url : "${ctxPath}/type/list",
dataType : 'text',
type : 'get',
async : false,
success : function(data) {
var obj = JSON.parse(data);
for (var i = 0; i < obj.length; i++) {
tree.add(obj[i].id, obj[i].pid, obj[i].name,
'javascript:setSrcValue(/''+ obj[i].name + '/',/''+ obj[i].pid+ '/')'
); 
}
var srcElement = null;
var valueElement = null;
showTree =function (item,valueId){
srcElement = window.event.srcElement;
valueElement = document.getElementById(valueId);
var x = getLeft(item);
var y = getTop(item) + item.offsetHeight;
var w = item.offsetWidth;
blockDTree(x,y,w);
}
setSrcValue=function (text,value){
srcElement.value = text;
valueElement.value = value;
hiddenDTree();
}
But my error is : Uncaught SyntaxError: missing ) after argument list.I don't know how to modify it? what's wrong with my code? what's the reason? #Jaromanda X
老铁,格式化下代码,你就可以从格式上看到问题所在了,最好用 ide,可以直接显示错误
try template string with backticks `.
for (var i = 0; i < obj.length; i++) {
tree.add(obj[i].id, obj[i].pid, obj[i].name,
`javascript:setSrcValue('${obj[i].name}' , '${obj[i].pid}')`);
}

ConverttoCSV is working but i want the view of the data to be changed in JavaScript Util-Factory in angularJS

var downloadCSV = function() {
var deferred = $q.defer();
var data = [
{"2013" : {}},
{"2014" : {}},
{"2015" : {}}
];
$q.all([
$http({
url: URLFactory.search(),
method: "POST",
data: formatParams(true,'2013')
}).then(function(d) {
data[0]["2013"] = d.data.response;
}),
$http({
url: URLFactory.search(),
method: "POST",
data: formatParams(true,'2014')
}).then(function(d) {
data[1]["2014"] = d.data.response;
}),
$http({
url: URLFactory.search(),
method: "POST",
data: formatParams(true,'2015')
}).then(function(d) {
data[2]["2015"] = d.data.response;
})
]).then(function(){
var r_data = formatData1(data);
var s_type_data = formatData2(data);
var m_cat_data = formatData3(data);
var r_data_csv = UtilsFactory.convertToCSV(r_data,"R 2013 - 2015", true);
var s_type_data_csv = UtilsFactory.convertToCSV(s_type_data,"S Type 2013 - 2015", true);
var m_cat_data_csv = UtilsFactory.convertToCSV(m_cat_data,"M Category 2013 - 2015", true);
var csv = region_data_csv +
spend_type_data_csv +
market_cat_data_csv;
deferred.resolve(csv);
});
return deferred.promise;
};
var formatData1 = function(data) {
var formatted = [];
var struct = {
"A" : {
"R" : "A"
},
"EE" : {
"R" : "EE"
},
"Gre" : {
"R" : "Gre"
}
}
for (var i = 0; i < data.length; i++) {
for (var j in data[i]) {
var r = data[i][j].RDATA;
var stype = data[i][j].STYPE.CURRENT;
for (var k = 0; k < r.length || k < stype.length; k++) {
struct[r[k].R][j + " (Mn " + currency_sym + ")"] [stype[k].STYPE] = parseFloat(r[k].VALUE + stype[k].VALUE).toFixed(2);
};
}
};
for (var i in struct) {
formatted.push(struct[i]);
};
return formatted;
};
var formatData2 = function(data) {
var formatted = [];
var struct = {
"Cl" : {
"S Type" : "Cl"
},
"Li" : {
"S Type" : "Li"
},
"Ma" : {
"S Type" : "Ma"
}
}
for (var i = 0; i < data.length; i++) {
for (var j in data[i]) {
var stype = data[i][j].STYPE.CURRENT;
for (var k = 0; k < stype.length; k++) {
struct[stype[k].STYPE][j + " (Mn " + currency_sym + ")"] = parseFloat(stype[k].VALUE).toFixed(2);
};
}
};
for (var i in struct) {
formatted.push(struct[i]);
};
return formatted;
};
Now i have 2 format data which displays r_data and s_type_data respectively in excel sheet with the help of convertToCSV.
The data is represented in tabular form like:
R 2013 - 2015
R 2013 2014 2015
A 2.5 NA NA
EE 1.5 NA NA
Gre 3 NA NA
S Type 2013-2015
S Type 2013 2014 2015
Cl 67 NA NA
Li 20 NA NA
Ma 19 NA NA
I want the data to appear as :
R S Type 2013 2014 2015
A Cl 0.5 NA NA
A Li 1.2 NA NA
A Ma 1.8 NA NA
Total 2.5
EE Cl
EE Li
EE Ma
Total 1.5
Can anyone tell me what should i change in struct statement? and also instead of 3 formatdata, can i accomplish this in one formatdata function ?
i tried putting stype data in formatdata1 but in console it says :
TypeError: Cannot set property 'Li' of undefined
at formatData1
enter code here
var deferred = $q.defer();
var data = [{
"2014": {}
}, {
"2015": {}
}];
$http({
url: URLFactory.searchxls(),
method: "POST",
data: formatParams(true)
}).then(function(response) {
var all_data = formatData1(response.data.response.ALLDATA);
var all_data_csv = UtilsFactory.convertToCSV(all_data, " 2014 - 2015", true);
var csv = all_data_csv;
deferred.resolve(csv);
});
return deferred.promise;
};
var formatData1 = function(data) {
var formatted = [];
var R = {
"R": {},
"S_type": {},
"2014": {},
"2015": {}
};
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].DATA.length; j++) {
var R = angular.copy(R);
R.R = data[i].col1name;
R.S_type = data[i].col2name;
for (var k = 0; k < data[i].DATA[j].Values.length; k++) {
R['Sum of ' + data[i].DATA[j].Values[k]['col_YEAR']]= parseFloat(data[i].DATA[j].Values[k].VALUE).toFixed(2);
}
formatted.push(R);
}
}
return formatted;
};

How to resolve something.something programmatically

I have following code:
;(function($){
var getWeatherInfo = function(url, requiredKeys ) {
var info = {},
dfd = $.Deferred();
$.getJSON( url, function( data ) {
for(var i = 0; i < requiredKeys.length; i++) {
info[requiredKeys[i]] = data[requiredKeys[i]];
}
dfd.resolve(info);
});
return dfd.promise();
};
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
requiredData = [
'name',
'coord.lat',
'coord.lon',
'description'
];
getWeatherInfo(url,requiredData).done(function(data){console.log(data)});
The data output is:
Object {name: "London", coord.lat: undefined, coord.lon: undefined, description: undefined}
Name is working fine because it doesn't have . How can I fix rest? I don't want to use eval. Is there any better alternative?
This will work:
$.getJSON( url, function( data ) {
for(var i = 0; i < requiredKeys.length; i++) {
if (requiredKeys[i].indexOf('.') > -1){
var ar = requiredKeys[i].split("\.");
info[requiredKeys[i]] = data[ar[0]][ar[1]]
}
else{
info[requiredKeys[i]] = data[requiredKeys[i]];
}
}
dfd.resolve(info);
});
Result: Object {name: "London", coord.lat: 51.51, coord.lon: -0.13, description: undefined}
http://jsfiddle.net/gpzd9w43/
EDIT:
Maybe a more elegant way to do it if you have more than 1 dot:
$.getJSON( url, function( data ) {
for(var i = 0; i < requiredKeys.length; i++) {
var ar = requiredKeys[i].split("\.");
var node = data;
for (var j = 0; j < ar.length; j++){
node = node[ar[j]];
}
info[requiredKeys[i]] = node;
}
dfd.resolve(info);
});
http://jsfiddle.net/gpzd9w43/1/

Storing result from FOR loop as one array (array only saves each results separately)

I have tried searching but can't find anything to help, maybe my problem is too simple! Anyway, I'm running an ajax request. The data given to the request is an array. Here is my code:
var id = "1#2#3#4#5#";
var chkdId = id.slice(0, -1);
var arr = chkdId.split('#');
var checkedId = '';
var chkdLen = arr.length;
for (var i = 0; i < chkdLen; i++) {
checkedId = arr[i];
var checkedId = checkedId;
var data = {};
var year = $('#year').val();
data["year"] = year;
data['type'] = "report";
data['accidentId'] = checkedId;
console.log(data);
ajax.readData('/report/readreport', data, null,
function (result) {
console.log(result);
},
function (error) {
alert('err ' + error);
}
);
}
request array:
Object {year:"2015" type: "report", accidentId: "1"}
Object {year:"2015" type: "report", accidentId: "2"}
Object {year:"2015" type: "report", accidentId: "3"}
Object {year:"2015" type: "report", accidentId: "4"}
Object {year:"2015" type: "report", accidentId: "5"}
result:
{"data":[{"name":aaaa,"age":"15"}]}
{"data":[{"name":bbb,"age":"25"}]}
{"data":[{"name":ccc,"age":"65"}]}
{"data":[{"name":ddd,"age":"45"}]}
{"data":[{"name":eee,"age":"24"}]}
How to store the results in a single array?
Here is my Solution
var id = "1#2#3#4#5#";
var chkdId = id.slice(0, -1);
console.log(chkdId);
var arr = chkdId.split('#');
var checkedId = '';
var chkdLen = arr.length;
// here is the array
var arrayWithResults = [];
for (var i = 0; i < chkdLen; i++) {
checkedId = arr[i];
var checkedId = checkedId;
var data = {};
var year = $('#year').val();
data["year"] = year;
data['type'] = "report";
data['accidentId'] = checkedId;
console.log(data);
ajax.readData('/report/readreport', data, null,
function (result) {
console.log(result);
// here you push in the requested data
arrayWithResults.push(result);
},
function (error) {
alert('err ' + error);
}
);
}
Take the ajax out of for. This will send only One ajax request to server and minimize the load on server.
var params = [];
for (var i = 0; i < chkdLen; i++) {
checkedId = arr[i];
var data = {};
var year = $('#year').val();
data["year"] = year;
data['type'] = "report";
data['accidentId'] = checkedId;
params.push(data);
// ^^^^^^^^^^^^^^
}
ajax.readData('/report/readreport', params, null,
// ^^^^^^
function (result) {
console.log(result);
},
function (error) {
alert('err ' + error);
}
);

handle javascripts objects with jquery

im using JSON to parse some data from MYSQL, but in order to bring all the information in just one call i´m tring to stored everything in JAVASCRIPT OBJECTS(works fine), the problem is i don`t know how can i use with JQUERY to fill in some divs and integrated the info of the objects with different functions. this is how i worked:
// SE DEFINE CADA OBJETO QUE RECIBE INFO DE CADA CAMPO DE BD
//PLATO
function PlatoBD(nombreplato , descripcion, caloriasTortilla, precio, ingredientes)
{
this.nombreplato = nombreplato;
this.descripcion = descripcion;
this.caloriasTortilla = caloriasTortilla;
this.precio = precio;
this.ingredientes = function(adiciones , NomPlato){
peticionBD(adiciones , NomPlato);
}
}
//ADICION
function AdicionBD(nombreAdicion , calXplato, tipoAdicion)
{
this.nombreAdicion = nombreAdicion;
this.calXplato = calXplato;
this.tipoAdicion = tipoAdicion;
}
//SE DEFINE LA FUNCION PARA LLAMAR CUALQUIER BASE DE DATOS
function peticionBD(peticionBDJSON,NomPlato){
$.post('php/consulta-actualizar-info.php',
{"peticionBD" :peticionBDJSON }
,
function(data) {
var infophpData = $.parseJSON(data);
if (peticionBDJSON == "menuElpaso") {
ingred = new Array();
for (var i = 0; i < infophpData.length; i++) {
window["plato_"+infophpData[i]["plato"].replace(' ','_')] = new PlatoBD(infophpData[i]["plato"] , infophpData[i]["descripcion"] , infophpData[i]["caloriasTortilla"] , infophpData[i]["precio"]);
window["plato_"+infophpData[i]["plato"].replace(' ','_')].ingredientes("adiciones",infophpData[i]["plato"].replace(' ',''))
};
};
if (peticionBDJSON == "adiciones") {
else if (NomPlato =="Burritoveggy")
{
for (var i = 0; i < infophpData.length; i++) {
window["adicionesPara"+NomPlato+"De"+infophpData[i]["adicion"].replace(" ","_")] = new AdicionBD(infophpData[i]["adicion"] , infophpData[i][NomPlato], infophpData[i]["tipoAdicion"]);
};
}
else if (NomPlato =="Quesadilla")
{
for (var i = 0; i < infophpData.length; i++) {
window["adicionesPara"+NomPlato+"De"+infophpData[i]["adicion"].replace(" ","_")] = new AdicionBD(infophpData[i]["adicion"] , infophpData[i][NomPlato], infophpData[i]["tipoAdicion"]);
};
}
...
};
}).error(
function(){
alert('Error al ejecutar la petición');
},
'json'
)
}
$(document).ready(function($){
peticionBD("menuElpaso","")
});
the response result is(http://wedesign-medellin.com/restaurante-elPaso/objeto-bd-domicilios.html):
PlatoBD {nombreplato: "Almuerzo", descripcion: "Sopa + elecciones + gaseosa", caloriasTortilla: "250", precio: "14.000", ingredientes: function}
Use jQuery.parseJSON(string_object)

Categories