All my AJAX requests are in json format which are being parsed in javascript.
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?
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' ?
To remove all null values from an object: Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array of keys. Check if each value is equal to null and delete the null values using the delete operator.
To find the difference between null and undefined, use the triple equality operator or Object is() method. To loosely check if the variable is null, use a double equality operator(==). The double equality operator can not tell the difference between null and undefined, so it counts as same.
In server side with PHP,
You can use array_filter
before json_encode
.
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);
The $result
contains:
{"0":"foo","2":-1}
As you see, the null elements are removed.
I'm going to add to the accepted answer because that will only work if you have a 1 dimensional object or array. If there is any array or object nesting then in order to get the accepted solution to work, you must create some sort of recursive array filter. Not ideal.
The best solution my colleague and I came up with was to actually perform a regular expression on the JSON string before it was returned from the server.
$json = json_encode($complexObject); echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $json);
The regular expression will remove all places in the string of the form ,"key":null
including any whitespace between the leading comma and the start of the key. It will also match "key":null,
afterwards to make sure that no null values were found at the beginning of a JSON object.
This isn't an ideal solution but it's far better than creating a recursive array filter given an object could be several dimensions deep. A better solution would be if json_encode
had a flag that let you specify if you wanted null entries to remain in the output string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With