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

时间:2015-03-14 19:55:02

标签: javascript jquery json

我有代码:

$(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:JSON数据第1行第3列的预期属性名称或'}'

我如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

不要使用字符串连接操作构建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

答案 1 :(得分:0)

那是因为你的“字符串”不是有效的JSON。在此处阅读有关JSON结构的更多信息:http://json.org/

此外,您已经使用JavaScript了,为什么在已经可以使用对象时构建JSON?

相关问题