1Catalyst::View::JSON(3)User Contributed Perl DocumentatioCnatalyst::View::JSON(3)
2
3
4

NAME

6       Catalyst::View::JSON - JSON view for your data
7

SYNOPSIS

9         # lib/MyApp/View/JSON.pm
10         package MyApp::View::JSON;
11         use base qw( Catalyst::View::JSON );
12         1;
13
14         # configure in lib/MyApp.pm
15         MyApp->config({
16             ...
17             'View::JSON' => {
18                 allow_callback  => 1,    # defaults to 0
19                 callback_param  => 'cb', # defaults to 'callback'
20                 expose_stash    => [ qw(foo bar) ], # defaults to everything
21             },
22         });
23
24         sub hello : Local {
25             my($self, $c) = @_;
26             $c->stash->{message} = 'Hello World!';
27             $c->forward('View::JSON');
28         }
29

DESCRIPTION

31       Catalyst::View::JSON is a Catalyst View handler that returns stash data
32       in JSON format.
33

CONFIG VARIABLES

35       allow_callback
36           Flag to allow callbacks by adding "callback=function". Defaults to
37           0 (doesn't allow callbacks). See "CALLBACKS" for details.
38
39       callback_param
40           Name of URI parameter to specify JSON callback function name.
41           Defaults to "callback". Only effective when "allow_callback" is
42           turned on.
43
44       expose_stash
45           Scalar, List or regular expression object, to specify which stash
46           keys are exposed as a JSON response. Defaults to everything.
47           Examples configuration:
48
49             # use 'json_data' value as a data to return
50             expose_stash => 'json_data',
51
52             # only exposes keys 'foo' and 'bar'
53             expose_stash => [ qw( foo bar ) ],
54
55             # only exposes keys that matches with /^json_/
56             expose_stash => qr/^json_/,
57
58           Suppose you have data structure of the following.
59
60             $c->stash->{foo} = [ 1, 2 ];
61             $c->stash->{bar} = [ 3, 4 ];
62
63           By default, this view will return:
64
65             {"foo":[1,2],"bar":2}
66
67           When you set "expose_stash => [ 'foo' ]", it'll return
68
69             {"foo":[1,2]}
70
71           and in the case of "expose_stash => 'foo'", it'll just return
72
73             [1,2]
74
75           instead of the whole object (hashref in perl). This option will be
76           useful when you share the method with different views (e.g. TT) and
77           don't want to expose non-irrelevant stash variables as in JSON.
78
79       json_driver
80             json_driver: JSON::Syck
81
82           By default this plugin uses JSON to encode the object, but you can
83           switch to the other drivers like JSON::Syck, whichever JSON::Any
84           supports.
85
86       no_x_json_header
87             no_x_json_header: 1
88
89           By default this plugin sets X-JSON header if the requested client
90           is a Prototype.js with X-JSON support. By setting 1, you can opt-
91           out this behavior so that you can do eval() by your own. Defaults
92           to 0.
93

OVERRIDING JSON ENCODER

95       By default it uses JSON::Any to serialize perl data strucuture into
96       JSON data format. If you want to avoid this and encode with your own
97       encoder (like passing options to JSON::XS etc.), you can implement
98       "encode_json" method in your View class.
99
100         package MyApp::View::JSON;
101         use base qw( Catalyst::View::JSON );
102
103         use JSON::XS ();
104
105         sub encode_json {
106             my($self, $c, $data) = @_;
107             my $encoder = JSON::XS->new->ascii->pretty->allow_nonref;
108             $encoder->encode($data);
109         }
110
111         1;
112

ENCODINGS

114       Due to the browser gotchas like those of Safari and Opera, sometimes
115       you have to specify a valid charset value in the response's Content-
116       Type header, e.g. "text/javascript; charset=utf-8".
117
118       Catalyst::View::JSON comes with the configuration variable "encoding"
119       which defaults to utf-8. You can change it via "YourApp->config" or
120       even runtime, using "component".
121
122         $c->component('View::JSON')->encoding('euc-jp');
123
124       This assumes you set your stash data in raw euc-jp bytes, or Unicode
125       flagged variable. In case of Unicode flagged variable,
126       Catalyst::View::JSON automatically encodes the data into your
127       "encoding" value (euc-jp in this case) before emitting the data to the
128       browser.
129
130       Another option would be to use JavaScript-UCS as an encoding (and pass
131       Unicode flagged string to the stash). That way all non-ASCII characters
132       in the output JSON will be automatically encoded to JavaScript Unicode
133       encoding like \uXXXX. You have to install Encode::JavaScript::UCS to
134       use the encoding.
135

CALLBACKS

137       By default it returns raw JSON data so your JavaScript app can deal
138       with using XMLHttpRequest calls. Adding callbacks (JSONP) to the API
139       gives more flexibility to the end users of the API: overcome the cross-
140       domain restrictions of XMLHttpRequest. It can be done by appending
141       script node with dynamic DOM manipulation, and associate callback
142       handler to the returned data.
143
144       For example, suppose you have the following code.
145
146         sub end : Private {
147             my($self, $c) = @_;
148             if ($c->req->param('output') eq 'json') {
149                 $c->forward('View::JSON');
150             } else {
151                 ...
152             }
153         }
154
155       "/foo/bar?output=json" will just return the data set in "$c->stash" as
156       JSON format, like:
157
158         { result: "foo", message: "Hello" }
159
160       but "/foo/bar?output=json&callback=handle_result" will give you:
161
162         handle_result({ result: "foo", message: "Hello" });
163
164       and you can write a custom "handle_result" function to handle the
165       returned data asynchronously.
166
167       The valid characters you can use in the callback function are
168
169         [a-zA-Z0-9\.\_\[\]]
170
171       but you can customize the behaviour by overriding the
172       "validate_callback_param" method in your View::JSON class.
173
174       See <http://developer.yahoo.net/common/json.html> and
175       http://ajaxian.com/archives/jsonp-json-with-padding
176       <http://ajaxian.com/archives/jsonp-json-with-padding> for more about
177       JSONP.
178

INTEROPERABILITY

180       JSON use is still developing and has not been standardized. This
181       section provides some notes on various libraries.
182
183       Dojo Toolkit: Setting dojo.io.bind's mimetype to 'text/json' in the
184       JavaScript request will instruct dojo.io.bind to expect JSON data in
185       the response body and auto-eval it. Dojo ignores the server response
186       Content-Type. This works transparently with Catalyst::View::JSON.
187
188       Prototype.js: prototype.js will auto-eval JSON data that is returned in
189       the custom X-JSON header. The reason given for this is to allow a
190       separate HTML fragment in the response body, however this of limited
191       use because IE 6 has a max header length that will cause the JSON
192       evaluation to silently fail when reached. The recommened approach is to
193       use Catalyst::View::JSON which will JSON format all the response data
194       and return it in the response body.
195
196       In at least prototype 1.5.0 rc0 and above, prototype.js will send the
197       X-Prototype-Version header. If this is encountered, a JavaScript eval
198       will be returned in the X-JSON resonse header to automatically eval the
199       response body, unless you set no_x_json_header to 1. If your version of
200       prototype does not send this header, you can manually eval the response
201       body using the following JavaScript:
202
203         evalJSON: function(request) {
204           try {
205             return eval('(' + request.responseText + ')');
206           } catch (e) {}
207         }
208         // elsewhere
209         var json = this.evalJSON(request);
210

SECURITY CONSIDERATION

212       Catalyst::View::JSON makes the data available as a (sort of) JavaScript
213       to the client, so you might want to be careful about the security of
214       your data.
215
216   Use callbacks only for public data
217       When you enable callbacks (JSONP) by setting "allow_callbacks", all
218       your JSON data will be available cross-site. This means embedding
219       private data of logged-in user to JSON is considered bad.
220
221         # MyApp.yaml
222         View::JSON:
223           allow_callbacks: 1
224
225         sub foo : Local {
226             my($self, $c) = @_;
227             $c->stash->{address} = $c->user->street_address; # BAD
228             $c->forward('View::JSON');
229         }
230
231       If you want to enable callbacks in a controller (for public API) and
232       disable in another, you need to create two different View classes, like
233       MyApp::View::JSON and MyApp::View::JSONP, because "allow_callbacks" is
234       a static configuration of the View::JSON class.
235
236       See http://ajaxian.com/archives/gmail-csrf-security-flaw
237       <http://ajaxian.com/archives/gmail-csrf-security-flaw> for more.
238
239   Avoid valid cross-site JSON requests
240       Even if you disable the callbacks, the nature of JavaScript still has a
241       possiblity to access private JSON data cross-site, by overriding Array
242       constructor "[]".
243
244         # MyApp.yaml
245         View::JSON:
246           expose_stash: json
247
248         sub foo : Local {
249             my($self, $c) = @_;
250             $c->stash->{json} = [ $c->user->street_address ]; # BAD
251             $c->forward('View::JSON');
252         }
253
254       When you return logged-in user's private data to the response JSON, you
255       might want to disable GET requests (because script tag invokes GET
256       requests), or include a random digest string and validate it.
257
258       See
259       http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techniques-using.html
260       <http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-
261       techniques-using.html> for more.
262

AUTHOR

264       Tatsuhiko Miyagawa <miyagawa@bulknews.net>
265

LICENSE

267       This library is free software; you can redistribute it and/or modify it
268       under the same terms as Perl itself.
269

CONTRIBUTORS

271       Following people has been contributing patches, bug reports and
272       suggestions for the improvement of Catalyst::View::JSON.
273
274       John Wang kazeburo Daisuke Murase Jun Kuriyama Tomas Doran
275

SEE ALSO

277       Catalyst, JSON, Encode::JavaScript::UCS
278
279       <http://www.prototypejs.org/learn/json>
280       <http://docs.jquery.com/Ajax/jQuery.getJSON>
281       <http://manual.dojotoolkit.org/json.html>
282       <http://developer.yahoo.com/yui/json/>
283
284
285
286perl v5.12.0                      2010-04-12           Catalyst::View::JSON(3)
Impressum