Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
Kérdezösködő Indián Avatar asked Dec 31 '25 22:12

Kérdezösködő Indián


1 Answers

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');
like image 56
Eduardo Veríssimo Avatar answered Jan 04 '26 14:01

Eduardo Veríssimo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!