无法从JSON数组对象获取值

时间:2015-06-01 06:34:01

标签: javascript arrays json

使用JSON.stringify我可以看到我有我的数据,但是对于我的生活如何循环并获取值,我想回到lat和lng并将它们传递给setMark(),注释掉现在。

function setMarkers(map) {
    var data = {
        optStatus: $("input[name='optStatus']:checked").attr("id"),
        sortOrder: $('#sortOrder').val()
    };
    var sTemp = "";

    $.ajax({
        type: 'GET',
        url: '/MeterReadsDue/getMarkers',
        async: true,
        dataType: 'json',
        success: function (data) {

            var myArray = data;
            $("#test1").append(JSON.stringify(data));

            //setMark(map,lat,lng);
        }
    });
}

DIV输出是下面的JSON字符串文本...

{
  "ContentEncoding": null,
  "ContentType": null,
  "Data": "[{'lat':55.86001,'lng':-4.24842,'content':'08ELSTER-X06A245926'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER11W722962'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER13M412917'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER14H760382'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER10M097604'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER11M763299'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER13W700357'},{'lat':55.86001,'lng':-4.24842,'content':'07100043500A012550'},{'lat':55.86001,'lng':-4.24842,'content':'07100043675521477'},{'lat':55.86001,'lng':-4.24842,'content':'07100330200M018100'},{'lat':55.86001,'lng':-4.24842,'content':'07100043582490025'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER04M227373'},{'lat':55.86001,'lng':-4.24842,'content':'08ELSTER-X88388817'},{'lat':55.86001,'lng':-4.24842,'content':'07100037098W006075'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER04M378296'},{'lat':55.86001,'lng':-4.24842,'content':'07100037187608261'},{'lat':55.86001,'lng':-4.24842,'content':'07100043587074857'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER83246929'},{'lat':55.86001,'lng':-4.24842,'content':'07100330205M086806'},{'lat':55.86001,'lng':-4.24842,'content':'06ELSTER07A091225'}]",
  "JsonRequestBehavior": 1,
  "MaxJsonLength": null,
  "RecursionLimit": null
}

1 个答案:

答案 0 :(得分:7)

如果查看输出的JSON,可以看到Data属性包含一个包含另一个类JSON字符串的字符串。不幸的是,它不是有效的JSON本身,因为它使用单引号而不是字符串的双引号。但是你很幸运,你的特定输出格式似乎没有包含双引号,所以你可以先替换它们然后解析它:

success: function (data) {
    var realData = data.Data.replace(/'/g, '"'); // replace single by double quotes
    realData = JSON.parse(realData); // parse JSON

    $("#test1").append(JSON.stringify(realData));

    // realData is an array of objects, so iterate over it
    realData.forEach(function (marker) {
         setMark(map, marker.lat, marker.lng);
    });
}