Catalyst-View-JSON-0.37/0000755000000000000000000000000013461325112015023 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/LICENSE0000644000000000000000000004345313461325112016041 0ustar00rootwheel00000000000000Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2019 by Tatsuhiko Miyagawa . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2019 by Tatsuhiko Miyagawa . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Catalyst-View-JSON-0.37/Changes0000644000000000000000000001367713461325044016340 0ustar00rootwheel00000000000000Revision history for Perl extension Catalyst::View::JSON 0.37 - 2019-04-28 - fix Makefile.PL when current directory not in @INC (perl 5.26+) - convert from Module::Install to Distar for release tooling - Drop unneeded prerequisite on YAML 0.36 Wed Nov 25 12:00:00 CT 2015 - POD updates, improved warning messages, strictness (andyjack++) - Make the default BOM added for safari optional. Possible breaking change, please file issues if this causes trouble. - New render method to let you just get a JSON encoded version of some data (Added to make compatible with the unofficial Catalyst View API that has a render method). - 0.35 Wed Jan 07 12:00:00 CT 2014 - Specify a version of JSON::MaybXS in the Makefile to close a test failure (test case requires version '1.003000' so we made that the required version). 0.34 Mon Jan 05 12:00:00 CT 2014 - switched from JSON::Any to JSON::MaybeXS (json_driver option no longer supported) - Updated some documenation to note that in 2015 perhaps some of the given advice is no longer relevent. - Added a new configuration option 'json_encoder_args' which lets you pass arguments to JSON::MaybeXS. Useful for when you want to have more control on how your JSON serializer works. 0.33 Tue Apr 12 12:20:22 PDT 2011 - Fixed local_request monkey patching to support Catalyst >= 5.89 0.32 Tue Jan 4 10:03:05 PST 2011 - remove Opera special casing (omega) 0.31 Wed Sep 15 15:14:33 PDT 2010 - Chrome doesn't like UTF-8 BOM (Larry Leszczynski) 0.30 Tue Apr 13 01:14:07 CEST 2010 - Fix test application to call $c->forward('View::JSON') rather than (the incorrect) $c->forward('MyApp::View::JSON') - Fix documentation to match the above change - Turn off the regex fallback behavior in the test applications on newer Catalyst versions to ensure tests are correctly forwarding. - Move actions out of the test application classes into controller classes to avoid deprecation warnings on newer Catalyst releases. - 0.29 had unintended commits accidentally pulled from ap/master. Reverted 0.28 Wed Mar 10 11:19:35 JST 2010 - No code changes. Fixed packaging, added YAML dep for testing 0.27 Tue Feb 23 18:09:02 PST 2010 - Added repository info to META.yml to satisfy people 0.26 Mon Aug 24 16:11:37 PDT 2009 - Work around not to expose Catalyst specific stash variables (Chris Prather) 0.25 Sat Apr 18 19:09:46 CST 2009 - Use MRO::Compat instead of NEXT. (Florian Ragwitz) 0.24 Mon Mar 3 01:42:30 PST 2008 - removed t/02_ut8.t since it doesn't do anything useful 0.23 Fri Feb 22 14:35:28 PST 2008 - Implemented and documented how to override JSON encoder in your view class by implementing encode_json() method. 0.22 Wed Jan 9 14:29:20 PST 2008 - Updated the test to work with JSON 2.x and now unbundle JSON.pm in inc/ (Thanks to Daniel Westermann-Clark) 0.21 Thu Oct 18 13:53:47 PDT 2007 - Update JSON::Any dependency to 1.11 (Thanks to typester and perigrin) 0.20 Wed Aug 29 03:23:27 PDT 2007 - Fixed POD config 'V::JSON' to 'View::JSON' (Thanks to Matt S Trout) 0.19 Fri Aug 3 15:32:04 PDT 2007 - Store JSON::Any object into json_dumper to prevent other modules to change JSON::Any backend like WWW::Facebook::API does. (Thanks to J.Shirley) 0.18 Mon Apr 30 21:08:06 PDT 2007 - Make 'JSON' as a default driver to make it backward compatible (Thanks to Andy Hobbs) 0.17 Wed Apr 25 16:04:44 PDT 2007 - Switch to Module::Install - include JSON.pm in inc/ for testing. (Thanks to Matt S Trout) 0.16 Tue Apr 17 20:11:38 PDT 2007 - Added JSON::Any dependency 0.15 Fri Apr 13 19:25:04 PDT 2007 - Switch to use JSON::Any to abstract JSON drivers imlementations (Thanks to Florian Ragwitz for the patch) 0.14 Wed Dec 20 17:20:26 PST 2006 - Oops, no_x_json_header in 0.13 was broken 0.13 Wed Dec 20 17:12:32 PST 2006 - Added UTF-8 BOM if the User-Agent is Safari and encoding is utf-8 (Jun Kuriyama) - Added 'no_x_json_header' option to disable auto-setting X-JSON for Prototype.js (Jun Kuriyama) - Documented json_driver config 0.12 Thu Oct 26 17:37:58 JST 2006 - Support X-JSON for Prototype.js (John Wang) - Updated interoperability doc (John Wang) 0.11 Mon Jul 31 16:21:14 JST 2006 - Fix validator so 'json_driver' should just work (Thanks to typester) 0.10 Sun Jul 30 23:46:43 JST 2006 - Updated document (Thanks to John Wang) - Switch Content-Type to application/json the standard other than Opera - Mention Encode::UCS::JavaScript in POD 0.09 Thu Apr 20 22:16:19 JST 2006 - Added Helper class (Thanks to Komatsu) 0.08 Tue Jan 10 13:31:39 UTC 2006 - Added Opera hack (Content-Type: applcation/x-javascript) (Thanks to kazeburo) 0.07 Tue Jan 10 13:00:19 UTC 2006 - Now able to use JSON::Syck as a converter by passing json_driver as 'JSON::Syck' 0.06 Tue Jan 10 09:04:34 UTC 2006 - Oops, 0.05 was broken. Fixed encode() problem and added test cases for them. 0.05 Tue Jan 10 08:51:02 UTC 2006 - Added encoding option (default utf-8) to tackle with Safari multibytes problem. Content-Type is now text/javascript (no +json) (Thanks to kazeburo) 0.04 Sun Jan 8 17:06:56 UTC 2006 - Added scalar support to expose_hash and updated the document. 0.03 Sun Jan 8 16:36:36 UTC 2006 - Added sanitization of callback function names to avoid XSS thingy. 0.02 Wed Jan 4 10:41:28 UTC 2006 - Include the tests file on distribution 0.01 Wed Jan 4 09:27:33 2006 - original version Catalyst-View-JSON-0.37/MANIFEST0000644000000000000000000000124613461325112016157 0ustar00rootwheel00000000000000Changes lib/Catalyst/Helper/View/JSON.pm lib/Catalyst/View/JSON.pm maint/Makefile.PL.include Makefile.PL MANIFEST This list of files t/00_compile.t t/01_server.t t/lib/TestApp.pm t/lib/TestApp/Controller/Root.pm t/lib/TestApp/View/JSON.pm t/lib/TestApp/View/JSON2.pm t/lib/TestAppUnicode.pm t/lib/TestAppUnicode/Controller/Root.pm t/lib/TestAppUnicode/View/JSON.pm META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) README README file (added by Distar) LICENSE LICENSE file (added by Distar) Catalyst-View-JSON-0.37/t/0000755000000000000000000000000013461325111015265 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/01_server.t0000644000000000000000000001207113461306233017265 0ustar00rootwheel00000000000000use strict; use warnings; use FindBin; use lib "$FindBin::Bin/lib"; use Encode; use Test::More; use Catalyst::Test 'TestApp'; use JSON::MaybeXS 1.003000 ':legacy'; plan tests => 47; BEGIN { no warnings 'redefine'; if ( $Catalyst::VERSION < 5.89 ) { *Catalyst::Test::local_request = sub { my ( $class, $request ) = @_; require HTTP::Request::AsCGI; my $cgi = HTTP::Request::AsCGI->new( $request, %ENV )->setup; $class->handle_request; return $cgi->restore->response; }; } else { *Catalyst::Test::local_request => sub { my ( $class, $request ) = @_; my $app = ref($class) eq "CODE" ? $class : $class->_finalized_psgi_app; my $ret; require Plack::Test; Plack::Test::test_psgi( app => sub { $app->(%{ $_[0] }) }, client => sub { $ret = shift->($request) }, ); return $ret; }; } } my $entrypoint = "http://localhost/foo"; { my $request = HTTP::Request->new( GET => $entrypoint ); ok( my $response = request($request), 'Request' ); ok( $response->is_success, 'Response Successful 2xx' ); is( $response->code, 200, 'Response Code' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); my $data = from_json($response->content); is $data->{json_foo}, "bar"; is_deeply $data->{json_baz}, [ 1, 2, 3 ]; ok ! $data->{foo}, "doesn't return stash that doesn't match json_"; } { my $request = HTTP::Request->new( GET => "http://localhost/foo2" ); ok( my $response = request($request), 'Request' ); ok( $response->is_success, 'Response Successful 2xx' ); is( $response->code, 200, 'Response Code' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); my $data = from_json($response->content); is_deeply( $data, [1, 2, 3] ); } { my $request = HTTP::Request->new( GET => $entrypoint . "?cb=foobar" ); ok( my $response = request($request), 'Request' ); ok( $response->is_success, 'Response Successful 2xx' ); is( $response->code, 200, 'Response Code' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); my $body = $response->content; ok $body =~ s/^foobar\((.*?)\);$/$1/sg, "wrapped in a callback"; my $data = from_json($body); is $data->{json_foo}, "bar"; is_deeply $data->{json_baz}, [ 1, 2, 3 ]; ok ! $data->{foo}, "doesn't return stash that doesn't match json_"; } { my $request = HTTP::Request->new( GET => $entrypoint . "?cb=foobar%28" ); ok( my $response = request($request), 'Request' ); like $response->header('X-Error'), qr/Invalid callback parameter/,; } { ## my $request = HTTP::Request->new( GET => "http://localhost/foo3" ); ok( my $response = request($request), 'Request' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); ok decode('utf-8', $response->content); } { my $request = HTTP::Request->new( GET => "http://localhost/foo4" ); ok( my $response = request($request), 'Request' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=euc-jp' ] ); ok decode('euc-jp', $response->content); } { my $request = HTTP::Request->new( GET => "http://localhost/foo3" ); $request->header("User-Agent", "Safari"); ok( my $response = request($request), 'Request' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); my $bom = substr $response->content, 0, 3; is $bom, "\xEF\xBB\xBF"; } { my $request = HTTP::Request->new( GET => "http://localhost/foo3" ); $request->header("User-Agent", "Safari"); ok( my $response = request($request), 'Request' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); my $bom = substr $response->content, 0, 3; is $bom, "\xEF\xBB\xBF"; } { my $request = HTTP::Request->new( GET => "http://localhost/foo3" ); $request->header("X-Prototype-Version", "1.5"); ok( my $response = request($request), 'Request' ); ok $response->header('X-JSON'); } { my $request = HTTP::Request->new( GET => "http://localhost/foo5" ); $request->header("X-Prototype-Version", "1.5"); ok( my $response = request($request), 'Request' ); ok !$response->header('X-JSON'); } { my $request = HTTP::Request->new( GET => "http://localhost/foo6" ); ok( my $response = request($request), 'Request' ); my $data = from_json($response->content); is $data->{foo}, "fake"; } { my $request = HTTP::Request->new( GET => "http://localhost/warnmsg" ); ok( my $response = request($request), 'Request' ); ok( $response->is_success, 'Response Successful 2xx' ); is( $response->code, 200, 'Response Code' ); is_deeply( [ $response->content_type ], [ 'application/json', 'charset=utf-8' ] ); my $data = from_json($response->content); is $data->{json_foo}, "bar"; is_deeply $data->{json_baz}, [ 1, 2, 3 ]; is $data->{'foo'}, 'barbarbar'; } Catalyst-View-JSON-0.37/t/00_compile.t0000644000000000000000000000012013461306233017376 0ustar00rootwheel00000000000000use strict; use Test::More tests => 1; BEGIN { use_ok 'Catalyst::View::JSON' } Catalyst-View-JSON-0.37/t/lib/0000755000000000000000000000000013461325111016033 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestApp/0000755000000000000000000000000013461325111017413 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestApp/Controller/0000755000000000000000000000000013461325111021536 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestApp/Controller/Root.pm0000644000000000000000000000324013461306233023022 0ustar00rootwheel00000000000000package TestApp::Controller::Root; use strict; use warnings; use base 'Catalyst::Controller'; __PACKAGE__->config(namespace => ''); sub foo : Global { my ( $self, $c ) = @_; $c->component('View::JSON')->expose_stash(qr/^json_/); $c->stash->{json_foo} = "bar"; $c->stash->{json_baz} = [ 1, 2, 3 ]; $c->stash->{foo} = "barbarbar"; $c->forward('View::JSON'); } sub warnmsg : Global { my ( $self, $c ) = @_; # case where setting expose_stash returns everything in # the stash. Set a true value to enter to code path # that shows the warning message. $c->component('View::JSON')->expose_stash(\1); $c->stash->{json_foo} = "bar"; $c->stash->{json_baz} = [ 1, 2, 3 ]; $c->stash->{foo} = "barbarbar"; $c->forward('View::JSON'); } sub foo2 : Global { my( $self, $c ) = @_; $c->component('View::JSON')->expose_stash('json_baz'); $c->stash->{json_foo} = "bar"; $c->stash->{json_baz} = [ 1, 2, 3 ]; $c->forward('View::JSON'); } sub foo3 : Global { my( $self, $c ) = @_; $c->stash->{json_foo} = "\x{5bae}\x{5ddd}"; $c->component('View::JSON')->encoding('utf-8'); $c->forward('View::JSON'); } sub foo4 : Global { my( $self, $c ) = @_; $c->stash->{json_foo} = "\x{5bae}\x{5ddd}"; $c->component('View::JSON')->encoding('euc-jp'); $c->forward('View::JSON'); } sub foo5 : Global { my( $self, $c ) = @_; $c->stash->{json_foo} = "\x{5bae}\x{5ddd}"; $c->component('View::JSON')->no_x_json_header(1); $c->forward('View::JSON'); } sub foo6 : Global { my( $self, $c ) = @_; $c->stash->{json_foo} = "\x{5bae}\x{5ddd}"; $c->forward('View::JSON2'); } 1; Catalyst-View-JSON-0.37/t/lib/TestApp/View/0000755000000000000000000000000013461325111020325 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestApp/View/JSON2.pm0000644000000000000000000000023213461306277021527 0ustar00rootwheel00000000000000package TestApp::View::JSON2; use base qw( Catalyst::View::JSON ); sub encode_json { my($self, $c, $data) = @_; return qq({"foo":"fake"}); } 1; Catalyst-View-JSON-0.37/t/lib/TestApp/View/JSON.pm0000644000000000000000000000010613461306233021435 0ustar00rootwheel00000000000000package TestApp::View::JSON; use base qw( Catalyst::View::JSON ); 1; Catalyst-View-JSON-0.37/t/lib/TestAppUnicode/0000755000000000000000000000000013461325111020722 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestAppUnicode/Controller/0000755000000000000000000000000013461325111023045 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestAppUnicode/Controller/Root.pm0000644000000000000000000000042513461306233024333 0ustar00rootwheel00000000000000package TestAppUnicode::Controller::Root; use strict; use warnings; use base 'Catalyst::Controller'; __PACKAGE__->config(namespace => ''); sub foo : Global { my ( $self, $c ) = @_; $c->stash->{foo} = "\x{30c6}\x{30b9}\x{30c8}"; $c->forward('View::JSON'); } 1; Catalyst-View-JSON-0.37/t/lib/TestAppUnicode/View/0000755000000000000000000000000013461325111021634 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/t/lib/TestAppUnicode/View/JSON.pm0000644000000000000000000000011513461306233022744 0ustar00rootwheel00000000000000package TestAppUnicode::View::JSON; use base qw( Catalyst::View::JSON ); 1; Catalyst-View-JSON-0.37/t/lib/TestApp.pm0000644000000000000000000000076113461306233017761 0ustar00rootwheel00000000000000package TestApp; use strict; use warnings; use MRO::Compat; use Catalyst; our $VERSION = '0.01'; __PACKAGE__->config({ name => 'TestApp', disable_component_resolution_regex_fallback => 1, 'View::JSON' => { use_force_bom => 1, expose_stash => qr/^json_/, allow_callback => 1, callback_param => 'cb', }, }); __PACKAGE__->setup; sub finalize_error { my $c = shift; $c->res->header('X-Error' => $c->error->[0]); $c->next::method; } 1; Catalyst-View-JSON-0.37/t/lib/TestAppUnicode.pm0000644000000000000000000000046213461306233021266 0ustar00rootwheel00000000000000package TestAppUnicode; use strict; use warnings; use Catalyst qw( Unicode ); __PACKAGE__->config({ name => 'TestAppUnicode', disable_component_resolution_regex_fallback => 1, 'View::JSON' => { allow_callback => 1, callback_param => 'cb', }, }); __PACKAGE__->setup; 1; Catalyst-View-JSON-0.37/README0000644000000000000000000003042613461325112015710 0ustar00rootwheel00000000000000NAME Catalyst::View::JSON - JSON view for your data SYNOPSIS # lib/MyApp/View/JSON.pm package MyApp::View::JSON; use base qw( Catalyst::View::JSON ); 1; # configure in lib/MyApp.pm MyApp->config({ ... 'View::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('View::JSON'); } DESCRIPTION Catalyst::View::JSON is a Catalyst View handler that returns stash data in JSON format. CONFIG VARIABLES allow_callback Flag to allow callbacks by adding "callback=function". Defaults to 0 (doesn't allow callbacks). See "CALLBACKS" for details. callback_param Name of URI parameter to specify JSON callback function name. Defaults to "callback". Only effective when "allow_callback" is turned on. expose_stash 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} = 2; By default, this view will return: {"foo":[1,2],"bar":2} When you set "expose_stash => [ 'foo' ]", it'll return {"foo":[1,2]} and in the case of "expose_stash => 'foo'", it'll just return [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. no_x_json_header no_x_json_header: 1 By default this plugin sets X-JSON header if the requested client is a Prototype.js with X-JSON support. By setting 1, you can opt-out this behavior so that you can do eval() by your own. Defaults to 0. json_encoder_args An optional hashref that supplies arguments to JSON::MaybeXS used when creating a new object. use_force_bom If versions of this view older than 0.36, there was some code that added a UTF-8 BOM marker to the end of the JSON string when the user agent was Safari. After looking at a lot of existing code I don't think this is needed anymore so we removed it by default. However if this turns out to be a problem you can re enable it by setting this attribute to true. Possible a breaking change so we offer this workaround. You may also override the method 'user_agent_bom_test' which received the current request user agent string to try and better determine if this is needed. Patches for this welcomed. METHODS process Standard target of $c->forward used to prepare a response render The methods accepts either of the following argument signatures in order to promote compatibility with the semi standard render method as define in numerous Catalyst views on CPAN: my $json_string = $c->view('JSON')->render($c, undef, $data); my $json_string = $c->view('JSON')->render($c, $data); Given '$data' returns the JSON serialized version, or throws and error. OVERRIDING JSON ENCODER By default it uses JSON::MaybeXS::encode_json to serialize perl data structure into JSON data format. If you want to avoid this and encode with your own encoder (like passing different options to JSON::MaybeXS etc.), you can implement the "encode_json" method in your View class. package MyApp::View::JSON; use base qw( Catalyst::View::JSON ); use JSON::MaybeXS (); sub encode_json { my($self, $c, $data) = @_; my $encoder = JSON::MaybeXS->new->(ascii => 1, pretty => 1, allow_nonref => 1); $encoder->encode($data); } 1; ENCODINGS NOTE Starting in release v5.90080 Catalyst encodes all text like body returns as UTF8. It however ignores content types like application/json and assumes that a correct JSON serializer is doing what it is supposed to do, which is encode UTF8 automatically. In general this is what this view does so you shoulding need to mess with the encoding flag here unless you have some odd case. Also, the comment about regard 'browser gotcha's' was written a number of years ago and I can't say one way or another if those gotchas continue to be common in the wild. NOTE Setting this configuation has no bearing on how the actual serialized string is encoded. This ONLY sets the content type header in your response. By default we set the 'utf8' flag on JSON::MaybeXS so that the string generated and set to your response body is proper UTF8 octets that can be transmitted over HTTP. If you are planning to do some alternative encoding you should turn off this default via the "json_encoder_args": MyApp::View::JSON->config( json_encoder_args => +{utf8=>0} ); NOTE In 2015 the use of UTF8 as encoding is widely standard so it is very likely you should need to do nothing to get the correct encoding. The following documentation will remain for historical value and backcompat needs. 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". 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". $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. CALLBACKS By default it returns raw JSON data so your JavaScript app can deal with using XMLHttpRequest calls. Adding callbacks (JSONP) 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('View::JSON'); } else { ... } } "/foo/bar?output=json" will just return the data set in "$c->stash" as JSON format, like: { result: "foo", message: "Hello" } but "/foo/bar?output=json&callback=handle_result" will give you: handle_result({ result: "foo", message: "Hello" }); and you can write a custom "handle_result" function to handle the returned data asynchronously. 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. See and for more about JSONP. NOTE For another way to enable JSONP in your application take a look at Plack::Middleware::JSONP INTEROPERABILITY 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 recommend approach is to use Catalyst::View::JSON which will JSON format all the response data and return it in the response body. In at least prototype 1.5.0 rc0 and above, prototype.js will send the X-Prototype-Version header. If this is encountered, a JavaScript eval will be returned in the X-JSON response header to automatically eval the response body, unless you set *no_x_json_header* to 1. If your version of prototype does not send this header, you can manually eval the response body using the following JavaScript: evalJSON: function(request) { try { return eval('(' + request.responseText + ')'); } catch (e) {} } // elsewhere var json = this.evalJSON(request); NOTE The above comments were written a number of years ago and I would take then with a grain of salt so to speak. For now I will leave them in place but not sure they are meaningful in 2015. SECURITY CONSIDERATION Catalyst::View::JSON makes the data available as a (sort of) JavaScript to the client, so you might want to be careful about the security of your data. Use callbacks only for public data When you enable callbacks (JSONP) by setting "allow_callback", all your JSON data will be available cross-site. This means embedding private data of logged-in user to JSON is considered bad. # MyApp.yaml View::JSON: allow_callback: 1 sub foo : Local { my($self, $c) = @_; $c->stash->{address} = $c->user->street_address; # BAD $c->forward('View::JSON'); } If you want to enable callbacks in a controller (for public API) and disable in another, you need to create two different View classes, like MyApp::View::JSON and MyApp::View::JSONP, because "allow_callback" is a static configuration of the View::JSON class. See for more. Avoid valid cross-site JSON requests Even if you disable the callbacks, the nature of JavaScript still has a possibility to access private JSON data cross-site, by overriding Array constructor "[]". # MyApp.yaml View::JSON: expose_stash: json sub foo : Local { my($self, $c) = @_; $c->stash->{json} = [ $c->user->street_address ]; # BAD $c->forward('View::JSON'); } When you return logged-in user's private data to the response JSON, you might want to disable GET requests (because *script* tag invokes GET requests), or include a random digest string and validate it. See for more. AUTHOR Tatsuhiko Miyagawa LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. CONTRIBUTORS Following people has been contributing patches, bug reports and suggestions for the improvement of Catalyst::View::JSON. John Wang kazeburo Daisuke Murase Jun Kuriyama Tomas Doran SEE ALSO Catalyst, JSON::MaybeXS, Encode::JavaScript::UCS Catalyst-View-JSON-0.37/META.yml0000644000000000000000000000152513461325111016276 0ustar00rootwheel00000000000000--- abstract: 'JSON view for your data' author: - 'Tatsuhiko Miyagawa ' build_requires: Test::More: '0.88' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Catalyst-View-JSON no_index: directory: - t - xt requires: Catalyst: '5.60' JSON::MaybeXS: '1.003000' MRO::Compat: '0' resources: bugtracker: https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-View-JSON license: http://dev.perl.org/licenses/ repository: https://github.com/perl-catalyst/Catalyst-View-JSON.git version: '0.37' x_authority: cpan:BOBTFISH x_breaks: {} x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Catalyst-View-JSON-0.37/lib/0000755000000000000000000000000013461325111015570 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/lib/Catalyst/0000755000000000000000000000000013461325111017354 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/lib/Catalyst/View/0000755000000000000000000000000013461325111020266 5ustar00rootwheel00000000000000Catalyst-View-JSON-0.37/lib/Catalyst/View/JSON.pm0000644000000000000000000003650513461324645021421 0ustar00rootwheel00000000000000package Catalyst::View::JSON; use strict; use warnings; our $VERSION = '0.37'; use 5.008_001; use base qw( Catalyst::View ); use Encode (); use MRO::Compat; use Catalyst::Exception; __PACKAGE__->mk_accessors(qw( allow_callback callback_param expose_stash encoding json_dumper no_x_json_header json_encoder_args use_force_bom)); sub new { my($class, $c, $arguments) = @_; my $self = $class->next::method($c); for my $field (keys %$arguments) { # Remove catalyst_component_name (and future Cat specific params) next if $field =~ /^catalyst/; # no longer supported warn('json_driver is no longer supported'), next if $field eq 'json_driver'; if ($self->can($field)) { $self->$field($arguments->{$field}); } else { $c->log->debug("Unknown config parameter '$field'"); } } if (my $method = $self->can('encode_json')) { $self->json_dumper( sub { my($data, $self, $c) = @_; $method->($self, $c, $data); } ); } else { require JSON::MaybeXS; my %args = (utf8=>1, %{$self->json_encoder_args ||+{}}); my $json = JSON::MaybeXS->new(%args); $self->json_dumper(sub { $json->encode($_[0]) }); } return $self; } sub process { my($self, $c) = @_; # get the response data from stash my $cond = sub { 1 }; my $single_key; if (my $expose = $self->expose_stash) { if (ref($expose) eq 'Regexp') { $cond = sub { $_[0] =~ $expose }; } elsif (ref($expose) eq 'ARRAY') { my %match = map { $_ => 1 } @$expose; $cond = sub { $match{$_[0]} }; } elsif (!ref($expose)) { $single_key = $expose; } else { $c->log->warn("expose_stash should be an array reference, Regexp object, or key for a single stash entry."); $c->log->warn("Returning all stash entries"); } } my $data; if ($single_key) { $data = $c->stash->{$single_key}; } else { $data = { map { $cond->($_) ? ($_ => $c->stash->{$_}) : () } keys %{$c->stash} }; } my $cb_param = $self->allow_callback ? ($self->callback_param || 'callback') : undef; my $cb = $cb_param ? $c->req->param($cb_param) : undef; $self->validate_callback_param($cb) if $cb; # When you set encoding option in View::JSON, this plugin DWIMs my $encoding = $self->encoding || 'utf-8'; $c->res->content_type("application/json; charset=$encoding"); if ($c->req->header('X-Prototype-Version') && !$self->no_x_json_header) { $c->res->header('X-JSON' => 'eval("("+this.transport.responseText+")")'); } my $json = $self->render($c, $data); my $output; ## add UTF-8 BOM if the client meets a test and the application wants it. if ($self->use_force_bom && $encoding eq 'utf-8') { my $user_agent = $c->req->user_agent || ''; if ($self->user_agent_bom_test($user_agent)) { $output = "\xEF\xBB\xBF"; } } $output .= "$cb(" if $cb; $output .= $json; $output .= ");" if $cb; $c->res->output($output); } # allow for called as $c, $template, $data || $c, $data so that we are compatible # with the semi standard render method that a lot of views use. sub render { my $self = shift; my $c = shift; my $data = pop; return $self->json_dumper->($data, $self, $c); # weird order to be backward compat } sub user_agent_bom_test { my ($self, $user_agent) = @_; return(($user_agent =~ m/\bSafari\b/) and ($user_agent !~ m/\bChrome\b/)); } sub validate_callback_param { my($self, $param) = @_; $param =~ /^[a-zA-Z0-9\.\_\[\]]+$/ or Catalyst::Exception->throw("Invalid callback parameter $param"); } 1; __END__ =head1 NAME Catalyst::View::JSON - JSON view for your data =head1 SYNOPSIS # lib/MyApp/View/JSON.pm package MyApp::View::JSON; use base qw( Catalyst::View::JSON ); 1; # configure in lib/MyApp.pm MyApp->config({ ... 'View::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('View::JSON'); } =head1 DESCRIPTION Catalyst::View::JSON is a Catalyst View handler that returns stash data in JSON format. =head1 CONFIG VARIABLES =over 4 =item allow_callback Flag to allow callbacks by adding C. Defaults to 0 (doesn't allow callbacks). See L for details. =item callback_param Name of URI parameter to specify JSON callback function name. Defaults to C. Only effective when C is turned on. =item expose_stash 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} = 2; By default, this view will return: {"foo":[1,2],"bar":2} When you set C<< expose_stash => [ 'foo' ] >>, it'll return {"foo":[1,2]} and in the case of C<< expose_stash => 'foo' >>, it'll just return [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. =item no_x_json_header no_x_json_header: 1 By default this plugin sets X-JSON header if the requested client is a Prototype.js with X-JSON support. By setting 1, you can opt-out this behavior so that you can do eval() by your own. Defaults to 0. =item json_encoder_args An optional hashref that supplies arguments to L used when creating a new object. =item use_force_bom If versions of this view older than 0.36, there was some code that added a UTF-8 BOM marker to the end of the JSON string when the user agent was Safari. After looking at a lot of existing code I don't think this is needed anymore so we removed it by default. However if this turns out to be a problem you can re enable it by setting this attribute to true. Possible a breaking change so we offer this workaround. You may also override the method 'user_agent_bom_test' which received the current request user agent string to try and better determine if this is needed. Patches for this welcomed. =back =head1 METHODS =head2 process Standard target of $c->forward used to prepare a response =head2 render The methods accepts either of the following argument signatures in order to promote compatibility with the semi standard render method as define in numerous L views on CPAN: my $json_string = $c->view('JSON')->render($c, undef, $data); my $json_string = $c->view('JSON')->render($c, $data); Given '$data' returns the JSON serialized version, or throws and error. =head1 OVERRIDING JSON ENCODER By default it uses L to serialize perl data structure into JSON data format. If you want to avoid this and encode with your own encoder (like passing different options to L etc.), you can implement the C method in your View class. package MyApp::View::JSON; use base qw( Catalyst::View::JSON ); use JSON::MaybeXS (); sub encode_json { my($self, $c, $data) = @_; my $encoder = JSON::MaybeXS->new->(ascii => 1, pretty => 1, allow_nonref => 1); $encoder->encode($data); } 1; =head1 ENCODINGS B Starting in release v5.90080 L encodes all text like body returns as UTF8. It however ignores content types like application/json and assumes that a correct JSON serializer is doing what it is supposed to do, which is encode UTF8 automatically. In general this is what this view does so you shoulding need to mess with the encoding flag here unless you have some odd case. Also, the comment about regard 'browser gotcha's' was written a number of years ago and I can't say one way or another if those gotchas continue to be common in the wild. B Setting this configuation has no bearing on how the actual serialized string is encoded. This ONLY sets the content type header in your response. By default we set the 'utf8' flag on L so that the string generated and set to your response body is proper UTF8 octets that can be transmitted over HTTP. If you are planning to do some alternative encoding you should turn off this default via the C: MyApp::View::JSON->config( json_encoder_args => +{utf8=>0} ); B In 2015 the use of UTF8 as encoding is widely standard so it is very likely you should need to do nothing to get the correct encoding. The following documentation will remain for historical value and backcompat needs. 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. C. Catalyst::View::JSON comes with the configuration variable C which defaults to utf-8. You can change it via C<< YourApp->config >> or even runtime, using C. $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 C value (euc-jp in this case) before emitting the data to the browser. Another option would be to use I 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 I<\uXXXX>. You have to install L to use the encoding. =head1 CALLBACKS By default it returns raw JSON data so your JavaScript app can deal with using XMLHttpRequest calls. Adding callbacks (JSONP) 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 I