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?

asked Aug 12, 2013 at 11:06

2 Answers 2

11

Try this

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});
});
answered Aug 12, 2013 at 11:09
Sign up to request clarification or add additional context in comments.

2 Comments

Bah! You beat me like a ginger step-child :) +1 Here's the fiddle I spent too long making jsfiddle.net/bzqZx
^^ ginger power! liked your answer more though, it was a lot cleaner
-3

Look JSON.parse method on MDN 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
answered Aug 12, 2013 at 11:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.