以编程方式创建json

时间:2013-08-12 11:06:00

标签: javascript jquery json

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

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

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

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

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

2 个答案:

答案 0 :(得分: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});
});

答案 1 :(得分:-3)

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

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