以编程方式创建json

Cor*_*ell 0 javascript jquery json

这是我试图以编程方式创建的JSON:

{
    "sensors": [{
        "x": 342,
        "y": 213,
        "id": 4
    }, {
        "x": 642,
        "y": 913,
        "id": 3
    }, {
        "x": 452,
        "y": 113,
        "id": 2
    }]
}
Run Code Online (Sandbox Code Playgroud)

我必须遍历具有特定类的所有元素来检索json的数据:

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

我怎么能像我描述的那样创建json对象?

Ant*_*ton 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});
});
Run Code Online (Sandbox Code Playgroud)