I am trying to create named Object in javascript like this: -
{
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]
}
and so on. I am getting country, latitude, longitude values from database. Below is my code: -
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++;
}
But I am getting the error "Uncaught SyntaxError: Unexpected string in JSON at position 7" . I think I am not creating the object in right way. Please help. Thanks in advance.
Edit
Here is what I have in countries_coord array a complete JSON: -
Afghanistan
:
Object
latitude
:
"33.93911"
longitude
:
"67.709953"
Australia
:
Object
latitude
:
"-25.274398"
longitude
:
"133.775136"
and so on I have another values in same format.
I miss-understood the question here is the solution
change
objFormat = '{"id:" "marker_""' + i + '","tooltip:" "' + country + '","src:" "//localhost/mapsvg/markers/pin1_red.png","width:" "'+ 15 + '","height:" "'+ 24 + '","geoCoords:" [ "'+ values.latitude + '", "'+values.longitude + '" ]}';
to
objFormat = '{"id": "marker_' + i + '",'+
'"tooltip": ' + country + '",'+
//etc
'"geoCoords": [ '+ values.latitude + ', '+values.longitude+' ]}';
Notice how I use the code indenting to make it easy to see when I have error. You had the quote after the colon.
A JSON object needs to be a single object or an array of objects so you want
[
{
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]
}
]
or
{
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]
}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.