Estoy tratando de crear un objeto con nombre en javascript como este: -
{ id: "marker_0", tooltip: country, src: "//localhost/mapsvg/markers/pin1_red.png", width: 15, height: 24, geoCoords: [latitude, longitude] }, { id: "marker_1", tooltip: country, src: "//localhost/mapsvg/markers/pin1_red.png", width: 15, height: 24, geoCoords: [latitude, longitude] }
y así. Obtengo valores de país, latitud y longitud de la base de datos. A continuación se muestra mi código: -
var objFormat; var i =0; var mapFormat = []; for (var country in countries_coord) { values = countries_coord[country]; objFormat = '{"id:" "marker_""' + i + '","tooltip:" "' + country + '","src:" "//localhost/mapsvg/markers/pin1_red.png","width:" "'+ 15 + '","height:" "'+ 24 + '","geoCoords:" [ "'+ values.latitude + '", "'+values.longitude + '" ]}'; obj = $.parseJSON(objFormat); mapFormat.push(objFormat); i++; }
Pero recibo el error "Error de sintaxis no detectado: cadena inesperada en JSON en la posición 7" . Creo que no estoy creando el objeto de la manera correcta. Por favor ayuda. Gracias por adelantado.
Editar
Esto es lo que tengo en la matriz country_coord un JSON completo: -
Afghanistan : Object latitude : "33.93911" longitude : "67.709953" Australia : Object latitude : "-25.274398" longitude : "133.775136"
y así sucesivamente tengo otros valores en el mismo formato.
No entendí bien la pregunta aquí está la solución
cambio
objFormat = '{"id:" "marker_""' + i + '","tooltip:" "' + country + '","src:" "//localhost/mapsvg/markers/pin1_red.png","width:" "'+ 15 + '","height:" "'+ 24 + '","geoCoords:" [ "'+ values.latitude + '", "'+values.longitude + '" ]}';
a
objFormat = '{"id": "marker_' + i + '",'+ '"tooltip": ' + country + '",'+ //etc '"geoCoords": [ '+ values.latitude + ', '+values.longitude+' ]}';
Observe cómo uso la sangría del código para que sea más fácil ver cuándo tengo un error. Tenías la cita después de los dos puntos.
Un objeto JSON debe ser un solo objeto o una matriz de objetos, por lo que desea
[ { id: "marker_0", tooltip: country, src: "//localhost/mapsvg/markers/pin1_red.png", width: 15, height: 24, geoCoords: [latitude, longitude] }, { id: "marker_1", tooltip: country, src: "//localhost/mapsvg/markers/pin1_red.png", width: 15, height: 24, geoCoords: [latitude, longitude] } ]
o
{ location_list: [ { id: "marker_0", tooltip: country, src: "//localhost/mapsvg/markers/pin1_red.png", width: 15, height: 24, geoCoords: [latitude, longitude] }, { id: "marker_1", tooltip: country, src: "//localhost/mapsvg/markers/pin1_red.png", width: 15, height: 24, geoCoords: [latitude, longitude] } ] }