Welcome Guest, Not a member yet? Register   Sign In
There is anyway to ignore null value from json response?
#1

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

Test for it or create a filter for it and place it on the route.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(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?
Reply
#4

No sample code, but you can look at filters in the CodeIgniter 4 User Guide. Also take a look at the HTTP responses.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

(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);
    }
}
Reply




Theme © iAndrew 2016 - Forum software by © MyBB