我正在尝试像这样在 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 SyntaxError: JSON 中位置 7 的意外字符串”。我想我没有以正确的方式创建对象。请帮忙。提前致谢。
编辑
这是我在 countries_coord 数组中拥有的完整 JSON:-
Afghanistan
:
Object
latitude
:
"33.93911"
longitude
:
"67.709953"
Australia
:
Object
latitude
:
"-25.274398"
longitude
:
"133.775136"
依此类推,我有另一个相同格式的值。
最佳答案
我误解了这里的问题是解决方案
改变
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]
}
]
}
关于javascript - 未捕获的语法错误 : Unexpected string in JSON at position 7 when using $. parseJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42770550/