简体   繁体   中英

how to convert DBIx::Class::ResultSet into JSON

I am trying to obtain JSON from a DBIx::Class::ResultSet and I get the exception

encountered object 'Sql2Json::Model::DB::Book=HASH(0x6014f88)', 
but neither allow_blessed, convert_blessed nor allow_tags settings are
enabled (or TO_JSON/FREEZE method missing)

The controller class is Books.pm :

package Sql2Json::Controller::Books;
use Moose;
use namespace::autoclean;
use JSON::XS;

BEGIN { extends 'Catalyst::Controller'; }

my $json = JSON::XS->new;

sub list : Local {
    my($self, $c) = @_;
    $c->stash(books_rs => $c->model('DB::Book'));
    $c->stash(books => [$c->stash->{books_rs}->search({}, {order_by => 'name ASC'})]);
    $c->stash(json_data => $json->convert_blessed->encode($c->stash->{books}));
    $c->forward('View::JSON');
}

__PACKAGE__->meta->make_immutable;

1;

According to this article is enough the encoding of blessed objects:

$json->convert_blessed->encode($c->stash->{books})

Do I missing somethig here?

Almost all the time, the best way to do this is using the get_inflated_column method of the rows returned from a query.

$books = $c->model('DB::Book');
$c->stash(json_data => [map {$_->get_inflated_columns} $books->all]);
$c->forward('View::JSON');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM