Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Valid JSON using CMS


Reply

5 Posts   1711 Views

Avatar
tv

11 September 2011 at 9:27am (Last edited: 11 September 2011 9:42am), Community Member, 44 Posts

I am trying to create a valid JSON string so that I can use Jquery .ajax to pull some events into different places on the web. I created a method on my EventsPage_Controller called jsonDates

   public function jsonDates() {
      $events = DataObject::get('Event');
      
      $output = array(); $i = 0;
      foreach($events as $event) {         
         $output[$i] = array(
            'start'   => $event->EventDate,
            'title'    => $event->EventTitle,
            'id'       => $event->ID,
            'thumb'   => $event->EventThumbnail()->Link(),
            'cover'   => $event->Image()->Link(),
            'desc'   => $event->Desc,
            'link'      => $event->EventLink,
         );   
      
         $i++;
      }
      
      return json_encode($output);
      
   }

Here's a snippet of the JSON i get when I navigate to mysite.com/events/jsonDates:

{"start":"2011-09-16 16:33:09","title":"Test Event","id":30,"thumb":"\/mysite.com\/assets\/","cover":"\/mysite.com\/assets\/","desc":"
This is a test event.<\/p>","link":"http:\/\/google.com"}

When I run the snippet above through JSON Lint, it seems to be choking on the space that the TinyMCE editor is placing in my description. There also seems to be an issue with the closing tags. I am getting this error:

Parse error on line 7:
...ets\/", "desc": "This is a test eve
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

Is this an issue of the CMS editor introducing unnecessary spaces?

Is there a better way of creating urls of JSON data using Silverstripe?

Avatar
Ryan M.

11 September 2011 at 11:11am Community Member, 309 Posts

It's not the spaces. It's all the backslashes that are there. Do a regexp to strip them before returning the JSON data.

Avatar
tv

12 September 2011 at 1:31am Community Member, 44 Posts

Thanks Ryan. I'll give it a try.

Avatar
tv

12 September 2011 at 3:18am Community Member, 44 Posts

Turns out the JSON was valid. When I ran the url itself through JSON Lint it returned as Valid.

I did notice that the page (mysite.com/events/jsonDates) has a Content-Type of 'text/html'. Maybe this is the source of the parse error. Is there a way to make it so that my Controller method returns a Content-Type of application/json when the page is visited?

Avatar
MarcusDalgren

12 September 2011 at 4:50am Community Member, 288 Posts

Yes you can do

$this->getResponse()->addHeader("Content-Type", "application/json; charset=utf-8");