开发者

What is the best way to trim a json data?

开发者 https://www.devze.com 2023-02-20 02:47 出处:网络
This is what I am currently doing to trim all of my value开发者_StackOverflow社区. It is ugly and a too repetitive.

This is what I am currently doing to trim all of my value开发者_StackOverflow社区. It is ugly and a too repetitive.

var strHTML = '';
$.getJSON('info.php',
    function(data) {
        $.each(data, function(i, item) {
            strHTML += $.trim(item.fname) +
                       $.trim(item.lname) +
                       $.trim(item.address) +
                       $.trim(item.phone) +
                       ...(about 10 more of these);
        });
    });

There ought to be a better way to do this.


A for...in example, with hasOwnProperty:

var obj = {
    foo: ' bar',
    blahblah: ' ahahaha   '
};

var arr = [];
for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        arr.push($.trim(obj[key]));
    }
}
alert(arr.join(','));


I'd say you should trim the data on the PHP-side, as it's your PHP script that generates it 1.

Basically : make sure your info.php script generates correct data.


In PHP, you can use the trim() function.

And if your data is stored in an array, you can apply that function to all items of that array using the array_map() function :

$data = array_map('trim', $data);


As a consequence, I will add the PHP tag to this question


If you want all properties of item to be trimmed you can use the for (props in item) {} -loop to loop through all of them. Because u can use this on all javascript-object you can create a function that does the trimming on all properties of an object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号