Catalyst::View::JSON - JSON view for your data
# lib/MyApp/View/JSON.pm package MyApp::View::JSON; use base qw( Catalyst::View::JSON ); 1; # configure in lib/MyApp.pm MyApp->config({ ... 'V::JSON' => { allow_callback => 1, # defaults to 0 callback_param => 'cb', # defaults to 'callback' expose_stash => [ qw(foo bar) ], # defaults to everything }, }); sub hello : Local { my($self, $c) = @_; $c->stash->{message} = 'Hello World!'; $c->forward('MyApp::View::JSON'); }
Catalyst::View::JSON is a Catalyst View handler that returns stash data in JSON format.
Flag to allow callbacks by adding callback=function. Defaults to 0 (doesn't allow callbacks). See "CALLBACKS" for details.
callback=function
Name of URI parameter to specify JSON callback function name. Defaults to callback. Only effective when allow_callback is turned on.
callback
allow_callback
Scalar, List or regular expression object, to specify which stash keys are exposed as a JSON response. Defaults to everything. Examples configuration:
# use 'json_data' value as a data to return expose_stash => 'json_data', # only exposes keys 'foo' and 'bar' expose_stash => [ qw( foo bar ) ], # only exposes keys that matches with /^json_/ expose_stash => qr/^json_/,
Suppose you have data structure of the following.
$c->stash->{foo} = [ 1, 2 ]; $c->stash->{bar} = [ 3, 4 ];
By default, this view will return:
{"foo":[1,2],"bar":2}
When you set expose_stash => [ 'foo' ], it'll return
expose_stash => [ 'foo' ]
{"foo":[1,2]}
and in the case of expose_stash => 'foo', it'll just return
expose_stash => 'foo'
[1,2]
instead of the whole object (hashref in perl). This option will be useful when you share the method with different views (e.g. TT) and don't want to expose non-irrelevant stash variables as in JSON.
Due to the browser gotchas like those of Safari and Opera, sometimes you have to specify a valid charset value in the response's Content-Type header, e.g. text/javascript; charset=utf-8.
text/javascript; charset=utf-8
Catalyst::View::JSON comes with the configuration variable encoding which defaults to utf-8. You can change it via YourApp->config or even runtime, using component.
encoding
YourApp->config
component
$c->component('View::JSON')->encoding('euc-jp');
This assumes you set your stash data in raw euc-jp bytes, or Unicode flagged variable. In case of Unicode flagged variable, Catalyst::View::JSON automatically encodes the data into your encoding value (euc-jp in this case) before emitting the data to the browser.
Another option would be to use JavaScript-UCS as an encoding (and pass Unicode flagged string to the stash). That way all non-ASCII characters in the output JSON will be automatically encoded to JavaScript Unicode encoding like \uXXXX. You have to install Encode::JavaScript::UCS to use the encoding.
By default it returns raw JSON data so your JavaScript app can deal with using XMLHttpRequest calls. Adding callbacks to the API gives more flexibility to the end users of the API: overcome the cross-domain restrictions of XMLHttpRequest. It can be done by appending script node with dynamic DOM manipulation, and associate callback handler to the returned data.
For example, suppose you have the following code.
sub end : Private { my($self, $c) = @_; if ($c->req->param('output') eq 'json') { $c->forward('MyApp::View::JSON'); } else { ... } }
/foo/bar?output=json will just return the data set in $c->stash as JSON format, like:
/foo/bar?output=json
$c->stash
{ result: "foo", message: "Hello" }
but /foo/bar?output=json&callback=handle_result will give you:
/foo/bar?output=json&callback=handle_result
handle_result({ result: "foo", message: "Hello" });
and you can write a custom handle_result function to handle the returned data asynchronously.
handle_result
The valid characters you can use in the callback function are
[a-zA-Z0-9\.\_\[\]]
but you can customize the behaviour by overriding the validate_callback_param method in your View::JSON class.
validate_callback_param
See Yahoo's nice explanation on http://developer.yahoo.net/common/json.html
JSON use is still developing and has not been standardized. This section provides some notes on various libraries.
Dojo Toolkit: Setting dojo.io.bind's mimetype to 'text/json' in the JavaScript request will instruct dojo.io.bind to expect JSON data in the response body and auto-eval it. Dojo ignores the server response Content-Type. This works transparently with Catalyst::View::JSON.
Prototype.js: prototype.js will auto-eval JSON data that is returned in the custom X-JSON header. The reason given for this is to allow a separate HTML fragment in the response body, however this of limited use because IE 6 has a max header length that will cause the JSON evaluation to silently fail when reached. The recommened approach is to use Catalyst::View::JSON which will JSON format all the response data and return it in the response body. The response body can then be evaled on the client using the following JavaScript:
evalJSON: function(request) { try { return eval('(' + request.responseText + ')'); } catch (e) {} } // elsewhere var json = this.evalJSON(request);
Tatsuhiko Miyagawa <miyagawa@bulknews.net>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Catalyst, JSON, Encode::JavaScript::UCS
To install Catalyst::View::JSON, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Catalyst::View::JSON
CPAN shell
perl -MCPAN -e shell install Catalyst::View::JSON
For more information on module installation, please visit the detailed CPAN module installation guide.