I am working on a Silverstripe project and I would like to have a simple way to present the content of a CMS generated Page (or subtype of Page) as JSON.
Ideally, I would like to append "/json" at the end of the route, or send a parameter via post (json=true) and obtain a response in JSON format.
I tried adding an action to my CustomPage_Controller class like this:
public static $allowed_actions = array('json');
public function json(SS_HTTPRequest $request) {
// ...
}
But I cannot figure out how to make that work:
You're on the right track. You'd simply do something like this in your json
action:
public function json(SS_HTTPRequest $request) {
$f = new JSONDataFormatter();
$this->response->addHeader('Content-Type', 'application/json');
return $f->convertDataObject($this->dataRecord);
}
Or for specific fields you could do this:
public function json(SS_HTTPRequest $request) {
// Encode specific fields
$data = array();
$data['ID'] = $this->dataRecord->ID;
$data['Title'] = $this->dataRecord->Title;
$data['Content'] = $this->dataRecord->Content;
$this->response->addHeader('Content-Type', 'application/json');
return json_encode($data);
}
If you put the above inside the controller in your Page.php file and all your other pages extend Page_Controller
then you should be able to go to http://mydomain/xxxx/json
and get the JSON output for any page.
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