Search code examples
phpjsonlithium

Requirements for JSON output


I'm not really sure whats required to make an action return json.
I'm sure there is more then one way to skin this cat, but I'm not sure what is absolutely required.

Is it adequate to just $this->render(array('json' => compact('data')); ?
Do I need to add a route specifying its json?
Do I also need to add the media type application/json?
Do I also need to add the default layout default.json.php?
Do I also need to add the view action.json.php?

Notes: I want any arbitrary url: www.mysite.com/Controller/Action to always return json.
I would prefer to be able to specify the return type in my action ONLY (ie, render type).


Solution

  • So it turns out nothing in the op is required other then this line when you return the data at the bottom of the controller action:

        return $this->render(array('json' => $data = array(), 'status'=> 200));
    

    Somethings which should be noted is that the data returned from a recordset is really ugly. Users should do a $recordset->to('array') first. Not sure why, but to('json') ends up escaping all the quotes, which makes the json string really funky.