删除json对象的null值 [英] strip null values of json object
问题描述
我所有的AJAX请求都是json格式,正在使用javascript进行解析.
All my AJAX requests are in json format which are being parsed in javascript.
如何避免在HTML页面中显示空值而无需在JavaScript中为每个json值编写if语句?
How can i prevent null values being displayed in an HTML page without needing to write an if-statement in javascript for each json value?
还是我应该编写一个自定义PHP函数以将数组编码为json而不是使用json_encode()以便它不显示"null"?
Or should i write a custom PHP function to encode an array to json instead of using json_encode() so it doesn't display 'null' ?
推荐答案
在使用PHP的服务器端,
In server side with PHP,
您可以在array_filter
.json-encode.php> json_encode
.
You can use array_filter
before json_encode
.
array_filter
会删除条目数组的 null 元素,例如:
array_filter
without second argument removes null elements of entry array, example :
$object= array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
$object = (object) array_filter((array) $object);
$result = json_encode($object);
$result
包含:
{"0":"foo","2":-1}
如您所见, null 元素被删除.
As you see, the null elements are removed.
这篇关于删除json对象的null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!