gpt4 book ai didi

javascript - 为什么 JSON 中的字符串变量不起作用?

转载 作者:行者123 更新时间:2023-12-03 10:34:42 26 4
gpt4 key购买 nike

我已经得到了代码:

$(document).ready(function() {

var adress = [];
var locations = ' [';
$('.office p').each(function(el) {
adress[el] = $(this).text();
locations = locations + '{address:\''+adress[el]+'\', data: \'0\', options:{icon: "http://selectner.com/img/bullet.png"}},';
});

locations = locations + ']';
console.log(locations);


$('#tablink').click(function (e) {

$('#map').gmap3({
map:{
options:{
center:[51.4675954,0.048876],
zoom: 2,
scrollwheel: true,
draggable: true,
}
},
marker:{
values : locations,
options:{
draggable: true
},
events:{
}
}
});
});
});

如果我复制 console.log 结果并将其粘贴到 JSON(在 gmap3 函数 - 位置位置)中 - 一切都会工作,但现在不起作用。

我认为,我必须使用 JSON.parse(),但它向我写入错误:

SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data

我该如何解决这个问题?

最佳答案

不要使用字符串连接操作构建 JSON。 只是不要永远,永远

您可以尝试使用简单的 JSON serializer这是为此目的而设计的,这样您就永远不会得到无效的 JSON:

var addresses = [];
$('.office p').each(function() {
addresses.push({
address: $(this).text(),
data: 0,
options: {
icon: 'http://selectner.com/img/bullet.png'
}
});
});

var locations = JSON.stringify(addresses);
console.log(locations);
// At this stage it is guaranteed that the addresses variable will
// contain valid JSON string

关于javascript - 为什么 JSON 中的字符串变量不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com