我试图在javascript中创建这样的命名对象:-
{
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]
}诸若此类。我正在从数据库中获取国家、纬度、经度值。以下是我的代码:-
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++;
}但是我得到了错误"Uncaught:位置7“处的JSON中的意外字符串。我认为我没有以正确的方式创建这个对象。请帮帮忙。提前谢谢。
编辑
下面是我在countries_coord数组中的一个完整的JSON:-
Afghanistan
:
Object
latitude
:
"33.93911"
longitude
:
"67.709953"
Australia
:
Object
latitude
:
"-25.274398"
longitude
:
"133.775136"等等,我有另一个相同格式的值。
发布于 2017-03-13 18:13:07
我不明白,这里的问题是解决办法。
变化
objFormat = '{"id:" "marker_""' + i + '","tooltip:" "' + country + '","src:" "//localhost/mapsvg/markers/pin1_red.png","width:" "'+ 15 + '","height:" "'+ 24 + '","geoCoords:" [ "'+ values.latitude + '", "'+values.longitude + '" ]}';至
objFormat = '{"id": "marker_' + i + '",'+
'"tooltip": ' + country + '",'+
//etc
'"geoCoords": [ '+ values.latitude + ', '+values.longitude+' ]}';请注意,我是如何使用代码缩进的,以便在出现错误时很容易看到。你在冒号后面有引号。
JSON对象需要是单个对象或对象数组,因此您需要
[
{
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]
}
]或
{
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]
}
]
}https://stackoverflow.com/questions/42770550
复制相似问题