Mojolicious - Can't parse JSON in RESTful

1.8k Views Asked by At

It's impossible to parse JSON in Mojolicious for me. I updated Mojolicious and used before following code, but JSON->new is deprecated.

my $json = Mojo::JSON->new;
my $user_request = $json->decode($c->req->body);
my $err = $json->error;

from the tutorials, I found out there has been added $self->req->json, but all POSTs to this will result into errors and non working code.

 curl -H "Content-Type: application/json" --data @body.json http://localhost:3000/checkaddress

and my body.json looks like this

{
       'id': 1
}

Here is my RESTful code in Mojolicious

post '/checkaddress' => sub {
my $self = shift;
my $dump = $self->dumper($self->req->json);
};

Console log

[Sat Feb 20 08:23:27 2016] [debug] 200 OK (0.001688s, 592.417/s)
[Sat Feb 20 08:24:38 2016] [debug] POST "/checkaddress"
[Sat Feb 20 08:24:38 2016] [debug] Routing to a callback
[Sat Feb 20 08:24:38 2016] [debug] undef

Calling $self->req->body and then decode_json from Mojo::JSON will result into

[error] Malformed JSON: Expected string while parsing object at line 1,  offset 5 at /home/aa/sempt2.pl line 15.

So, how to parse JSON correctly now?

2

There are 2 best solutions below

0
On BEST ANSWER

This works with Mojolicious 6.25 and is a complete example:

package MyREST;
use Mojo::Base 'Mojolicious';

use Data::Dumper;

sub startup {
  my $app = shift;

  my $routes = $app->routes;

  $routes->post('/checkaddress' => sub {
    my $self = shift;
    my $data = $self->req->json;
    my $dump = $self->dumper($self->req->json);
    print STDERR $dump;
    $self->render(json => $data);
  });

}

1;

For convenience and reliable testing a small client script:

#!perl

use strict;
use warnings;

use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $tx = $ua->post('http://localhost:3000/checkaddress' => json =>
  {
    'id'  => "1",
  }
);

This script avoids JSON encoding problems.

Even better would be, to write tests in the Mojolicious style.

0
On

I solved it!

{
   'id': 1
}

it needs to be replaced to

{
  "id": 1
}

and then id can be then accessed with

my $test = decode_json($self->req->body);
$test->{id};

And the shortened way

my $test = $self->req->json;
$test->{id};

is working too!

The errors occured because of the wrong json encoding '', which needs to be "". Hope it helps someone.