jhthorsen / json-validator

:cop: Validate data against a JSON schema
https://metacpan.org/release/JSON-Validator
56 stars 58 forks source link

spec.json cant't include unicode charater #179

Closed zhumengu closed 4 years ago

zhumengu commented 4 years ago

Steps to reproduce the behavior

Run sample code

use Mojolicious::Lite;

# Will be moved under "basePath", resulting in "POST /api/echo"
post "/echo" => sub {

  # Validate input request or return an error document
  my $c = shift->openapi->valid_input or return;

  # Generate some data
  my $data = {body => $c->validation->param("body")};

  # Validate the output response and render it to the user agent
  # using a custom "openapi" handler.
  $c->render(openapi => $data);
}, "echo";

# Load specification and start web server
plugin OpenAPI => {url => "data:///spec.json"};
app->start;

__DATA__
@@ spec.json
{
  "swagger" : "2.0",
  "info" : { "version": "0.8", "title" : "Echo **中文**" },
  "schemes" : [ "http" ],
  "basePath" : "/api",
  "paths" : {
    "/echo" : {
      "post" : {
        "x-mojo-name" : "echo",
        "parameters" : [
          { "in": "body", "name": "body", "schema": { "type" : "object" } }
        ],
        "responses" : {
          "200": {
            "description": "Echo response",
            "schema": { "type": "object" }
          }
        }
      }
    }
  }
}

Expected behavior

no error

Actual behavior

Input is not UTF-8 encoded at ~/perl5/lib/perl5/JSON/Validator.pm line 358. JSON::Validator.pm JSON::Validator::_load_schema_from_text

  return Mojo::JSON::decode_json($$text) if $$text =~ /^\s*\{/s;

change to this no error

 return Mojo::JSON::from_json($$text) if $$text =~ /^\s*\{/s;
Grinnz commented 4 years ago

This is because the DATA contents are decoded by the implicit use utf8 from Mojolicious::Lite, and decode_json expects encoded bytes

jhthorsen commented 4 years ago

Fixed in ddec049.