CodeIgniter Forums
There is anyway to ignore null value from json response? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: There is anyway to ignore null value from json response? (/showthread.php?tid=80187)



There is anyway to ignore null value from json response? - 2k10cs86 - 09-25-2021

I have build REST API and I want to ignore the null value from the response, is there any way to do that?


RE: There is anyway to ignore null value from json response? - InsiteFX - 09-26-2021

Test for it or create a filter for it and place it on the route.


RE: There is anyway to ignore null value from json response? - 2k10cs86 - 09-26-2021

(09-26-2021, 12:20 AM)InsiteFX Wrote: Test for it or create a filter for it and place it on the route.

Sorry, but not clear what do you mean? Do you have a sample code to share?


RE: There is anyway to ignore null value from json response? - InsiteFX - 09-26-2021

No sample code, but you can look at filters in the CodeIgniter 4 User Guide. Also take a look at the HTTP responses.


RE: There is anyway to ignore null value from json response? - 2k10cs86 - 09-26-2021

(09-26-2021, 03:26 AM)InsiteFX Wrote: No sample code, but you can look at filters in the CodeIgniter 4 User Guide. Also take a look at the HTTP responses.

Thanks for the tip, I have solved that by below filter:

Register in $global 'after' App/Filters.php
Code:
<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class JsonFilter implements FilterInterface
{
    function __construct()
    {
    }

    public function before(RequestInterface $request, $arguments = null)
    {
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        $json = $response->getJSON();
        $body = preg_replace('/,\s*"[^"]+": null|"[^"]+": null,?/', '', $json);
        $response->setJSON($body);
    }
}