0

This is the JSON I'm trying to create programmatically:

{
    "sensors": [{
        "x": 342,
        "y": 213,
        "id": 4
    }, {
        "x": 642,
        "y": 913,
        "id": 3
    }, {
        "x": 452,
        "y": 113,
        "id": 2
    }]
}

I have to iterate through all elements with a specific class to retrieve the data for the json:

$(".marker").each(function()
{
    var x = $(this).attr("data-x");
    var y = $(this).attr("data-y");
    var id = $(this).attr("data-id");
});

How could I create the json object to be like I described?

4

2 回答 2

11

尝试这个

var json = {"sensors":[]};

$(".marker").each(function()
{
    var x = $(this).attr("data-x");
    var y = $(this).attr("data-y");
    var id = $(this).attr("data-id");
    json.sensors.push({"x":x, "y":y,"id":id});
});
于 2013-08-12T11:09:36.420 回答
-3

在 MDN 或 MSDN 上查看 JSON.parse 方法

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);

// Output: Aaberg, Jesper
于 2013-08-12T11:12:18.657 回答