Filtering JSON data with JQUERY Filtering JSON data with JQUERY json json

Filtering JSON data with JQUERY


I don't get why you'd want to remove anything from the JSON if you need to loop through it anyway to print messages (at least that's what your sample leads me to think).

So I'd just add this condition to your JS:

$.each(json.data, function(i, data){    if(data.from.id != 234 && data.from.name != 'Alan Ford'){        $("#inbox").append(            '<div class="post">'+            'To: '+data.to.name+''+            ''+data.subject+''+            ''+data.message_formatted+''+            'added: '+data.date_sent_formatted.formatted+''+            'Sender: '+data.from.name+''+            '<hr />'+            '</div>'        );    }});​

Also, you might want to properly escape every variable you're printing by replacing dangerous characters yourself or using the .text() function from jQuery.


Last advice: editing the DOM takes time, so you'd better append only once if you plan on handling a lot of messages:

var output = '';$.each(json.data, function(i, data){    if(data.from.id != 234 && data.from.name != 'Alan Ford'){        output +=            '<div class="post">'+            'To: '+data.to.name+''+            ''+data.subject+''+            ''+data.message_formatted+''+            'added: '+data.date_sent_formatted.formatted+''+            'Sender: '+data.from.name+''+            '<hr />'+            '</div>';    }});$("#inbox").append(output);​

Here's the thing: http://jsfiddle.net/pioul/Hy2nd/