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} = 2;
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       no_x_json_header
80             no_x_json_header: 1
81
82           By default this plugin sets X-JSON header if the requested client
83           is a Prototype.js with X-JSON support. By setting 1, you can opt-
84           out this behavior so that you can do eval() by your own. Defaults
85           to 0.
86
87       json_encoder_args
88           An optional hashref that supplies arguments to JSON::MaybeXS used
89           when creating a new object.
90
91       use_force_bom
92           If versions of this view older than 0.36, there was some code that
93           added a UTF-8 BOM marker to the end of the JSON string when the
94           user agent was Safari.  After looking at a lot of existing code I
95           don't think this is needed anymore so we removed it by default.
96           However if this turns out to be a problem you can re enable it by
97           setting this attribute to true.  Possible a breaking change so we
98           offer this workaround.
99
100           You may also override the method 'user_agent_bom_test' which
101           received the current request user agent string to try and better
102           determine if this is needed.  Patches for this welcomed.
103

METHODS

105   process
106       Standard target of $c->forward used to prepare a response
107
108   render
109       The methods accepts either of the following argument signatures in
110       order to promote compatibility with the semi standard render method as
111       define in numerous Catalyst views on CPAN:
112
113           my $json_string = $c->view('JSON')->render($c, undef, $data);
114           my $json_string = $c->view('JSON')->render($c, $data);
115
116       Given '$data' returns the JSON serialized version, or throws and error.
117

OVERRIDING JSON ENCODER

119       By default it uses JSON::MaybeXS::encode_json to serialize perl data
120       structure into JSON data format. If you want to avoid this and encode
121       with your own encoder (like passing different options to JSON::MaybeXS
122       etc.), you can implement the "encode_json" method in your View class.
123
124         package MyApp::View::JSON;
125         use base qw( Catalyst::View::JSON );
126
127         use JSON::MaybeXS ();
128
129         sub encode_json {
130             my($self, $c, $data) = @_;
131             my $encoder = JSON::MaybeXS->new->(ascii => 1, pretty => 1, allow_nonref => 1);
132             $encoder->encode($data);
133         }
134
135         1;
136

ENCODINGS

138       NOTE Starting in release v5.90080 Catalyst encodes all text like body
139       returns as UTF8.  It however ignores content types like
140       application/json and assumes that a correct JSON serializer is doing
141       what it is supposed to do, which is encode UTF8 automatically.  In
142       general this is what this view does so you shoulding need to mess with
143       the encoding flag here unless you have some odd case.
144
145       Also, the comment aboe regard 'browser gotcha's' was written a number
146       of years ago and I can't say one way or another if those gotchas
147       continue to be common in the wild.
148
149       NOTE Setting this configuation has no bearing on how the actual
150       serialized string is encoded.  This ONLY sets the content type header
151       in your response.  By default we set the 'utf8' flag on JSON::MaybeXS
152       so that the string generated and set to your response body is proper
153       UTF8 octets that can be transmitted over HTTP.  If you are planning to
154       do some alternative encoding you should turn off this default via the
155       "json_encoder_args":
156
157           MyApp::View::JSON->config(
158             json_encoder_args => +{utf8=>0} );
159
160       NOTE In 2015 the use of UTF8 as encoding is widely standard so it is
161       very likely you should need to do nothing to get the correct encoding.
162       The following documention will remain for historical value and
163       backcompat needs.
164
165       Due to the browser gotchas like those of Safari and Opera, sometimes
166       you have to specify a valid charset value in the response's Content-
167       Type header, e.g. "text/javascript; charset=utf-8".
168
169       Catalyst::View::JSON comes with the configuration variable "encoding"
170       which defaults to utf-8. You can change it via "YourApp->config" or
171       even runtime, using "component".
172
173         $c->component('View::JSON')->encoding('euc-jp');
174
175       This assumes you set your stash data in raw euc-jp bytes, or Unicode
176       flagged variable. In case of Unicode flagged variable,
177       Catalyst::View::JSON automatically encodes the data into your
178       "encoding" value (euc-jp in this case) before emitting the data to the
179       browser.
180
181       Another option would be to use JavaScript-UCS as an encoding (and pass
182       Unicode flagged string to the stash). That way all non-ASCII characters
183       in the output JSON will be automatically encoded to JavaScript Unicode
184       encoding like \uXXXX. You have to install Encode::JavaScript::UCS to
185       use the encoding.
186

CALLBACKS

188       By default it returns raw JSON data so your JavaScript app can deal
189       with using XMLHttpRequest calls. Adding callbacks (JSONP) to the API
190       gives more flexibility to the end users of the API: overcome the cross-
191       domain restrictions of XMLHttpRequest. It can be done by appending
192       script node with dynamic DOM manipulation, and associate callback
193       handler to the returned data.
194
195       For example, suppose you have the following code.
196
197         sub end : Private {
198             my($self, $c) = @_;
199             if ($c->req->param('output') eq 'json') {
200                 $c->forward('View::JSON');
201             } else {
202                 ...
203             }
204         }
205
206       "/foo/bar?output=json" will just return the data set in "$c->stash" as
207       JSON format, like:
208
209         { result: "foo", message: "Hello" }
210
211       but "/foo/bar?output=json&callback=handle_result" will give you:
212
213         handle_result({ result: "foo", message: "Hello" });
214
215       and you can write a custom "handle_result" function to handle the
216       returned data asynchronously.
217
218       The valid characters you can use in the callback function are
219
220         [a-zA-Z0-9\.\_\[\]]
221
222       but you can customize the behaviour by overriding the
223       "validate_callback_param" method in your View::JSON class.
224
225       See <http://developer.yahoo.net/common/json.html> and
226       <http://ajaxian.com/archives/jsonp-json-with-padding> for more about
227       JSONP.
228
229       NOTE For another way to enable JSONP in your application take a look at
230       Plack::Middleware::JSONP
231

INTEROPERABILITY

233       JSON use is still developing and has not been standardized. This
234       section provides some notes on various libraries.
235
236       Dojo Toolkit: Setting dojo.io.bind's mimetype to 'text/json' in the
237       JavaScript request will instruct dojo.io.bind to expect JSON data in
238       the response body and auto-eval it. Dojo ignores the server response
239       Content-Type. This works transparently with Catalyst::View::JSON.
240
241       Prototype.js: prototype.js will auto-eval JSON data that is returned in
242       the custom X-JSON header. The reason given for this is to allow a
243       separate HTML fragment in the response body, however this of limited
244       use because IE 6 has a max header length that will cause the JSON
245       evaluation to silently fail when reached. The recommend approach is to
246       use Catalyst::View::JSON which will JSON format all the response data
247       and return it in the response body.
248
249       In at least prototype 1.5.0 rc0 and above, prototype.js will send the
250       X-Prototype-Version header. If this is encountered, a JavaScript eval
251       will be returned in the X-JSON response header to automatically eval
252       the response body, unless you set no_x_json_header to 1. If your
253       version of prototype does not send this header, you can manually eval
254       the response body using the following JavaScript:
255
256         evalJSON: function(request) {
257           try {
258             return eval('(' + request.responseText + ')');
259           } catch (e) {}
260         }
261         // elsewhere
262         var json = this.evalJSON(request);
263
264       NOTE The above comments were written a number of years ago and I would
265       take then with a grain of salt so to speak.  For now I will leave them
266       in place but not sure they are meaningful in 2015.
267

SECURITY CONSIDERATION

269       Catalyst::View::JSON makes the data available as a (sort of) JavaScript
270       to the client, so you might want to be careful about the security of
271       your data.
272
273   Use callbacks only for public data
274       When you enable callbacks (JSONP) by setting "allow_callback", all your
275       JSON data will be available cross-site. This means embedding private
276       data of logged-in user to JSON is considered bad.
277
278         # MyApp.yaml
279         View::JSON:
280           allow_callback: 1
281
282         sub foo : Local {
283             my($self, $c) = @_;
284             $c->stash->{address} = $c->user->street_address; # BAD
285             $c->forward('View::JSON');
286         }
287
288       If you want to enable callbacks in a controller (for public API) and
289       disable in another, you need to create two different View classes, like
290       MyApp::View::JSON and MyApp::View::JSONP, because "allow_callback" is a
291       static configuration of the View::JSON class.
292
293       See <http://ajaxian.com/archives/gmail-csrf-security-flaw> for more.
294
295   Avoid valid cross-site JSON requests
296       Even if you disable the callbacks, the nature of JavaScript still has a
297       possibility to access private JSON data cross-site, by overriding Array
298       constructor "[]".
299
300         # MyApp.yaml
301         View::JSON:
302           expose_stash: json
303
304         sub foo : Local {
305             my($self, $c) = @_;
306             $c->stash->{json} = [ $c->user->street_address ]; # BAD
307             $c->forward('View::JSON');
308         }
309
310       When you return logged-in user's private data to the response JSON, you
311       might want to disable GET requests (because script tag invokes GET
312       requests), or include a random digest string and validate it.
313
314       See
315       <http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techniques-using.html>
316       for more.
317

AUTHOR

319       Tatsuhiko Miyagawa <miyagawa@bulknews.net>
320

LICENSE

322       This library is free software; you can redistribute it and/or modify it
323       under the same terms as Perl itself.
324

CONTRIBUTORS

326       Following people has been contributing patches, bug reports and
327       suggestions for the improvement of Catalyst::View::JSON.
328
329         John Wang
330         kazeburo
331         Daisuke Murase
332         Jun Kuriyama
333         Tomas Doran
334

SEE ALSO

336       Catalyst, JSON::MaybeXS, Encode::JavaScript::UCS
337
338       <http://www.prototypejs.org/learn/json>
339       <http://docs.jquery.com/Ajax/jQuery.getJSON>
340       <http://manual.dojotoolkit.org/json.html>
341       <http://developer.yahoo.com/yui/json/>
342
343
344
345perl v5.28.1                      2015-11-25           Catalyst::View::JSON(3)
Impressum