Question

I use DBIx class for selecting data from database; I send response from controller to client using serialization to json using Catalyst::View::JSON

But utf8-data selected from database needs to be decoded to perl-string from utf-8 before sending to client like this

use Encode;

...

sub get_fruits :Path('getfruits') :Args(0) {
    my $fruits = [$c->model('DB::Fruit')->search({})->hashref_array];
    # Hated encode data loop
    foreach (@$fruits) {
        $_->{name} = decode('utf8', $_->{name});
    }
    $c->stash({fruits => $fruits});
    $c->forward('View::JSON');
}

Is it possible to decode data automatically in the View?

Was it helpful?

Solution 2

This may be as simple as ensuring that Catalyst::View::JSON is using a JSON encoder that supports UTF8 encoding. I believe that if you use JSON::XS with Catalyst::View::JSON it will perform UTF8 encoding by default. You can make sure that Catalyst::View::JSON is using JSON::XS using the json_driver config variable.

Alternatively you can override JSON encoding in Catalyst::View::JSON as detailed in the docs

OTHER TIPS

The Catalyst model always has to ensure that the data is decoded, regardless of where it is used. The view has to ensure the data is encoded correctly. You have to make sure that your model decodes data coming from the database. If you are using DBIx::Class read Using Unicode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top