| 1 |
NAME |
| 2 |
Catalyst::View::JSON - JSON view for your data |
| 3 |
|
| 4 |
SYNOPSIS |
| 5 |
# lib/MyApp/View/JSON.pm |
| 6 |
package MyApp::View::JSON; |
| 7 |
use base qw( Catalyst::View::JSON ); |
| 8 |
1; |
| 9 |
|
| 10 |
# configure in lib/MyApp.pm |
| 11 |
MyApp->config({ |
| 12 |
... |
| 13 |
'View::JSON' => { |
| 14 |
allow_callback => 1, # defaults to 0 |
| 15 |
callback_param => 'cb', # defaults to 'callback' |
| 16 |
expose_stash => [ qw(foo bar) ], # defaults to everything |
| 17 |
}, |
| 18 |
}); |
| 19 |
|
| 20 |
sub hello : Local { |
| 21 |
my($self, $c) = @_; |
| 22 |
$c->stash->{message} = 'Hello World!'; |
| 23 |
$c->forward('View::JSON'); |
| 24 |
} |
| 25 |
|
| 26 |
DESCRIPTION |
| 27 |
Catalyst::View::JSON is a Catalyst View handler that returns stash data |
| 28 |
in JSON format. |
| 29 |
|
| 30 |
CONFIG VARIABLES |
| 31 |
allow_callback |
| 32 |
Flag to allow callbacks by adding "callback=function". Defaults to 0 |
| 33 |
(doesn't allow callbacks). See "CALLBACKS" for details. |
| 34 |
|
| 35 |
callback_param |
| 36 |
Name of URI parameter to specify JSON callback function name. |
| 37 |
Defaults to "callback". Only effective when "allow_callback" is |
| 38 |
turned on. |
| 39 |
|
| 40 |
expose_stash |
| 41 |
Scalar, List or regular expression object, to specify which stash |
| 42 |
keys are exposed as a JSON response. Defaults to everything. |
| 43 |
Examples configuration: |
| 44 |
|
| 45 |
# use 'json_data' value as a data to return |
| 46 |
expose_stash => 'json_data', |
| 47 |
|
| 48 |
# only exposes keys 'foo' and 'bar' |
| 49 |
expose_stash => [ qw( foo bar ) ], |
| 50 |
|
| 51 |
# only exposes keys that matches with /^json_/ |
| 52 |
expose_stash => qr/^json_/, |
| 53 |
|
| 54 |
Suppose you have data structure of the following. |
| 55 |
|
| 56 |
$c->stash->{foo} = [ 1, 2 ]; |
| 57 |
$c->stash->{bar} = 2; |
| 58 |
|
| 59 |
By default, this view will return: |
| 60 |
|
| 61 |
{"foo":[1,2],"bar":2} |
| 62 |
|
| 63 |
When you set "expose_stash => [ 'foo' ]", it'll return |
| 64 |
|
| 65 |
{"foo":[1,2]} |
| 66 |
|
| 67 |
and in the case of "expose_stash => 'foo'", it'll just return |
| 68 |
|
| 69 |
[1,2] |
| 70 |
|
| 71 |
instead of the whole object (hashref in perl). This option will be |
| 72 |
useful when you share the method with different views (e.g. TT) and |
| 73 |
don't want to expose non-irrelevant stash variables as in JSON. |
| 74 |
|
| 75 |
no_x_json_header |
| 76 |
no_x_json_header: 1 |
| 77 |
|
| 78 |
By default this plugin sets X-JSON header if the requested client is |
| 79 |
a Prototype.js with X-JSON support. By setting 1, you can opt-out |
| 80 |
this behavior so that you can do eval() by your own. Defaults to 0. |
| 81 |
|
| 82 |
json_encoder_args |
| 83 |
An optional hashref that supplies arguments to JSON::MaybeXS used |
| 84 |
when creating a new object. |
| 85 |
|
| 86 |
use_force_bom |
| 87 |
If versions of this view older than 0.36, there was some code that |
| 88 |
added a UTF-8 BOM marker to the end of the JSON string when the user |
| 89 |
agent was Safari. After looking at a lot of existing code I don't |
| 90 |
think this is needed anymore so we removed it by default. However if |
| 91 |
this turns out to be a problem you can re enable it by setting this |
| 92 |
attribute to true. Possible a breaking change so we offer this |
| 93 |
workaround. |
| 94 |
|
| 95 |
You may also override the method 'user_agent_bom_test' which |
| 96 |
received the current request user agent string to try and better |
| 97 |
determine if this is needed. Patches for this welcomed. |
| 98 |
|
| 99 |
METHODS |
| 100 |
process |
| 101 |
Standard target of $c->forward used to prepare a response |
| 102 |
|
| 103 |
render |
| 104 |
The methods accepts either of the following argument signatures in order |
| 105 |
to promote compatibility with the semi standard render method as define |
| 106 |
in numerous Catalyst views on CPAN: |
| 107 |
|
| 108 |
my $json_string = $c->view('JSON')->render($c, undef, $data); |
| 109 |
my $json_string = $c->view('JSON')->render($c, $data); |
| 110 |
|
| 111 |
Given '$data' returns the JSON serialized version, or throws and error. |
| 112 |
|
| 113 |
OVERRIDING JSON ENCODER |
| 114 |
By default it uses JSON::MaybeXS::encode_json to serialize perl data |
| 115 |
structure into JSON data format. If you want to avoid this and encode |
| 116 |
with your own encoder (like passing different options to JSON::MaybeXS |
| 117 |
etc.), you can implement the "encode_json" method in your View class. |
| 118 |
|
| 119 |
package MyApp::View::JSON; |
| 120 |
use base qw( Catalyst::View::JSON ); |
| 121 |
|
| 122 |
use JSON::MaybeXS (); |
| 123 |
|
| 124 |
sub encode_json { |
| 125 |
my($self, $c, $data) = @_; |
| 126 |
my $encoder = JSON::MaybeXS->new->(ascii => 1, pretty => 1, allow_nonref => 1); |
| 127 |
$encoder->encode($data); |
| 128 |
} |
| 129 |
|
| 130 |
1; |
| 131 |
|
| 132 |
ENCODINGS |
| 133 |
NOTE Starting in release v5.90080 Catalyst encodes all text like body |
| 134 |
returns as UTF8. It however ignores content types like application/json |
| 135 |
and assumes that a correct JSON serializer is doing what it is supposed |
| 136 |
to do, which is encode UTF8 automatically. In general this is what this |
| 137 |
view does so you shoulding need to mess with the encoding flag here |
| 138 |
unless you have some odd case. |
| 139 |
|
| 140 |
Also, the comment about regard 'browser gotcha's' was written a number |
| 141 |
of years ago and I can't say one way or another if those gotchas |
| 142 |
continue to be common in the wild. |
| 143 |
|
| 144 |
NOTE Setting this configuation has no bearing on how the actual |
| 145 |
serialized string is encoded. This ONLY sets the content type header in |
| 146 |
your response. By default we set the 'utf8' flag on JSON::MaybeXS so |
| 147 |
that the string generated and set to your response body is proper UTF8 |
| 148 |
octets that can be transmitted over HTTP. If you are planning to do some |
| 149 |
alternative encoding you should turn off this default via the |
| 150 |
"json_encoder_args": |
| 151 |
|
| 152 |
MyApp::View::JSON->config( |
| 153 |
json_encoder_args => +{utf8=>0} ); |
| 154 |
|
| 155 |
NOTE In 2015 the use of UTF8 as encoding is widely standard so it is |
| 156 |
very likely you should need to do nothing to get the correct encoding. |
| 157 |
The following documentation will remain for historical value and |
| 158 |
backcompat needs. |
| 159 |
|
| 160 |
Due to the browser gotchas like those of Safari and Opera, sometimes you |
| 161 |
have to specify a valid charset value in the response's Content-Type |
| 162 |
header, e.g. "text/javascript; charset=utf-8". |
| 163 |
|
| 164 |
Catalyst::View::JSON comes with the configuration variable "encoding" |
| 165 |
which defaults to utf-8. You can change it via "YourApp->config" or even |
| 166 |
runtime, using "component". |
| 167 |
|
| 168 |
$c->component('View::JSON')->encoding('euc-jp'); |
| 169 |
|
| 170 |
This assumes you set your stash data in raw euc-jp bytes, or Unicode |
| 171 |
flagged variable. In case of Unicode flagged variable, |
| 172 |
Catalyst::View::JSON automatically encodes the data into your "encoding" |
| 173 |
value (euc-jp in this case) before emitting the data to the browser. |
| 174 |
|
| 175 |
Another option would be to use *JavaScript-UCS* as an encoding (and pass |
| 176 |
Unicode flagged string to the stash). That way all non-ASCII characters |
| 177 |
in the output JSON will be automatically encoded to JavaScript Unicode |
| 178 |
encoding like *\uXXXX*. You have to install Encode::JavaScript::UCS to |
| 179 |
use the encoding. |
| 180 |
|
| 181 |
CALLBACKS |
| 182 |
By default it returns raw JSON data so your JavaScript app can deal with |
| 183 |
using XMLHttpRequest calls. Adding callbacks (JSONP) to the API gives |
| 184 |
more flexibility to the end users of the API: overcome the cross-domain |
| 185 |
restrictions of XMLHttpRequest. It can be done by appending *script* |
| 186 |
node with dynamic DOM manipulation, and associate callback handler to |
| 187 |
the returned data. |
| 188 |
|
| 189 |
For example, suppose you have the following code. |
| 190 |
|
| 191 |
sub end : Private { |
| 192 |
my($self, $c) = @_; |
| 193 |
if ($c->req->param('output') eq 'json') { |
| 194 |
$c->forward('View::JSON'); |
| 195 |
} else { |
| 196 |
... |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
"/foo/bar?output=json" will just return the data set in "$c->stash" as |
| 201 |
JSON format, like: |
| 202 |
|
| 203 |
{ result: "foo", message: "Hello" } |
| 204 |
|
| 205 |
but "/foo/bar?output=json&callback=handle_result" will give you: |
| 206 |
|
| 207 |
handle_result({ result: "foo", message: "Hello" }); |
| 208 |
|
| 209 |
and you can write a custom "handle_result" function to handle the |
| 210 |
returned data asynchronously. |
| 211 |
|
| 212 |
The valid characters you can use in the callback function are |
| 213 |
|
| 214 |
[a-zA-Z0-9\.\_\[\]] |
| 215 |
|
| 216 |
but you can customize the behaviour by overriding the |
| 217 |
"validate_callback_param" method in your View::JSON class. |
| 218 |
|
| 219 |
See <http://developer.yahoo.net/common/json.html> and |
| 220 |
<http://ajaxian.com/archives/jsonp-json-with-padding> for more about |
| 221 |
JSONP. |
| 222 |
|
| 223 |
NOTE For another way to enable JSONP in your application take a look at |
| 224 |
Plack::Middleware::JSONP |
| 225 |
|
| 226 |
INTEROPERABILITY |
| 227 |
JSON use is still developing and has not been standardized. This section |
| 228 |
provides some notes on various libraries. |
| 229 |
|
| 230 |
Dojo Toolkit: Setting dojo.io.bind's mimetype to 'text/json' in the |
| 231 |
JavaScript request will instruct dojo.io.bind to expect JSON data in the |
| 232 |
response body and auto-eval it. Dojo ignores the server response |
| 233 |
Content-Type. This works transparently with Catalyst::View::JSON. |
| 234 |
|
| 235 |
Prototype.js: prototype.js will auto-eval JSON data that is returned in |
| 236 |
the custom X-JSON header. The reason given for this is to allow a |
| 237 |
separate HTML fragment in the response body, however this of limited use |
| 238 |
because IE 6 has a max header length that will cause the JSON evaluation |
| 239 |
to silently fail when reached. The recommend approach is to use |
| 240 |
Catalyst::View::JSON which will JSON format all the response data and |
| 241 |
return it in the response body. |
| 242 |
|
| 243 |
In at least prototype 1.5.0 rc0 and above, prototype.js will send the |
| 244 |
X-Prototype-Version header. If this is encountered, a JavaScript eval |
| 245 |
will be returned in the X-JSON response header to automatically eval the |
| 246 |
response body, unless you set *no_x_json_header* to 1. If your version |
| 247 |
of prototype does not send this header, you can manually eval the |
| 248 |
response body using the following JavaScript: |
| 249 |
|
| 250 |
evalJSON: function(request) { |
| 251 |
try { |
| 252 |
return eval('(' + request.responseText + ')'); |
| 253 |
} catch (e) {} |
| 254 |
} |
| 255 |
// elsewhere |
| 256 |
var json = this.evalJSON(request); |
| 257 |
|
| 258 |
NOTE The above comments were written a number of years ago and I would |
| 259 |
take then with a grain of salt so to speak. For now I will leave them in |
| 260 |
place but not sure they are meaningful in 2015. |
| 261 |
|
| 262 |
SECURITY CONSIDERATION |
| 263 |
Catalyst::View::JSON makes the data available as a (sort of) JavaScript |
| 264 |
to the client, so you might want to be careful about the security of |
| 265 |
your data. |
| 266 |
|
| 267 |
Use callbacks only for public data |
| 268 |
When you enable callbacks (JSONP) by setting "allow_callback", all your |
| 269 |
JSON data will be available cross-site. This means embedding private |
| 270 |
data of logged-in user to JSON is considered bad. |
| 271 |
|
| 272 |
# MyApp.yaml |
| 273 |
View::JSON: |
| 274 |
allow_callback: 1 |
| 275 |
|
| 276 |
sub foo : Local { |
| 277 |
my($self, $c) = @_; |
| 278 |
$c->stash->{address} = $c->user->street_address; # BAD |
| 279 |
$c->forward('View::JSON'); |
| 280 |
} |
| 281 |
|
| 282 |
If you want to enable callbacks in a controller (for public API) and |
| 283 |
disable in another, you need to create two different View classes, like |
| 284 |
MyApp::View::JSON and MyApp::View::JSONP, because "allow_callback" is a |
| 285 |
static configuration of the View::JSON class. |
| 286 |
|
| 287 |
See <http://ajaxian.com/archives/gmail-csrf-security-flaw> for more. |
| 288 |
|
| 289 |
Avoid valid cross-site JSON requests |
| 290 |
Even if you disable the callbacks, the nature of JavaScript still has a |
| 291 |
possibility to access private JSON data cross-site, by overriding Array |
| 292 |
constructor "[]". |
| 293 |
|
| 294 |
# MyApp.yaml |
| 295 |
View::JSON: |
| 296 |
expose_stash: json |
| 297 |
|
| 298 |
sub foo : Local { |
| 299 |
my($self, $c) = @_; |
| 300 |
$c->stash->{json} = [ $c->user->street_address ]; # BAD |
| 301 |
$c->forward('View::JSON'); |
| 302 |
} |
| 303 |
|
| 304 |
When you return logged-in user's private data to the response JSON, you |
| 305 |
might want to disable GET requests (because *script* tag invokes GET |
| 306 |
requests), or include a random digest string and validate it. |
| 307 |
|
| 308 |
See |
| 309 |
<http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techni |
| 310 |
ques-using.html> for more. |
| 311 |
|
| 312 |
AUTHOR |
| 313 |
Tatsuhiko Miyagawa <[email protected]> |
| 314 |
|
| 315 |
LICENSE |
| 316 |
This library is free software; you can redistribute it and/or modify it |
| 317 |
under the same terms as Perl itself. |
| 318 |
|
| 319 |
CONTRIBUTORS |
| 320 |
Following people has been contributing patches, bug reports and |
| 321 |
suggestions for the improvement of Catalyst::View::JSON. |
| 322 |
|
| 323 |
John Wang |
| 324 |
kazeburo |
| 325 |
Daisuke Murase |
| 326 |
Jun Kuriyama |
| 327 |
Tomas Doran |
| 328 |
|
| 329 |
SEE ALSO |
| 330 |
Catalyst, JSON::MaybeXS, Encode::JavaScript::UCS |
| 331 |
|
| 332 |
<http://www.prototypejs.org/learn/json> |
| 333 |
<http://docs.jquery.com/Ajax/jQuery.getJSON> |
| 334 |
<http://manual.dojotoolkit.org/json.html> |
| 335 |
<http://developer.yahoo.com/yui/json/> |
| 336 |
|