5

If I have the following DOM elements

<div class="item">content1</div>
<div class="item">content2</div>

how, using jQuery and Javascript, do I construct a JSON object like the following?

[{ 
'classname': 'item',
'content': 'content1'
}
{
'classname': 'item',
'content': 'content2'
}]

Any recommended further reading?

4
  • Why do you want to do this? Sometimes the best representation of the data is the data itself. Commented Mar 29, 2012 at 19:55
  • Consider keeping your data in a MVC model, not the DOM... Commented Mar 29, 2012 at 19:56
  • I'm trying to construct a JSON table like that used here: links.sourceforge.net/timeline/js/examples/… But instead of writing the html in the json object directly, I wanted to write the html in the DOM, and then construct the json object. Is this the best way of going about it? Commented Mar 29, 2012 at 20:04
  • This is the object he uses in the example, but it seems messy to write the html as such. ta = [ { 'start': new Date(2010,7,23), 'content': 'Conversation<br><img src="img/comments-icon.png" style="width:32px; height:32px;">' }, Commented Mar 29, 2012 at 20:07

3 Answers 3

7
var data = $('div.item').map(function(){
    return {
        classname: 'item',
        content: $(this).text()
    };
}).get();

DEMO: http://jsfiddle.net/nDE7e/

Sign up to request clarification or add additional context in comments.

4 Comments

Nice. What are the merits of doing it this way over using .each() ?
.map will return you an array, instead of having to make one beforehand.
Nice approach. It looks like you can get rid about the last .get().
@aschuler: The .get() is there so that you're returned an array. Otherwise, you're returned a jQuery object.
2

http://jsfiddle.net/24JjD/

var datas = [{ 
    'classname': 'item',
    'content': 'content1'
    }, {
    'classname': 'item',
    'content': 'content2'
    }
];

$.each(datas, function(key, value) {
    $('body').append('<div class="'+value.classname+'">'+value.content+'</div>');
});​

Correct answer :

http://jsfiddle.net/tS9r5/

var datas = [];

$('div.item').each(function() {
   var data = { 
       classname: this.className, 
       content: $(this).text()
   };
   datas.push(data);
});

console.log(datas);

Comments

0

You can loop over the item divs and add objects to an array.

var items = new Array();

$("div.item").each(function() {
   var item = {classname: this.className, content: $(this).text()};
   items.push(item);
});

Comments

Your Answer

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.