开发者

How do I find the difference between normal text and the JSON encoded text in Perl?

I have used JSON::Any in my program to transfer the hash between client and server.

I faced one problem, I want to find whether the text (sent by client) is norm开发者_StackOverflowal text or JSON encoded text.

Can anyone please tell me how to find,

without checking, I got some error in server side and it is closed.


You can't do it without checking. The most simple approach is to just do the decoding and then handle the exception.

use JSON::Any;
use Try::Tiny;

my $perl_data;
for my $perhaps_json (
    q(this won't decode), q({"how":"ever", "this":"will"}),
) {
    try {
        $perl_data = JSON::Any->jsonToObj($perhaps_json);
    } catch {
        warn "decoding failed: $_\n";
    }
}
say "Even with invalid input, I did not crash!";
__END__
decoding failed: 'true' expected, at character offset 0 (before "this won't decode") at .../lib/perl5/site_perl/5.10.1/JSON/Any.pm line 529.

Even with invalid input, I did not crash!


Well, if you are sending JSON in HTTP messages, you should be using the correct JSON MIME type. When you get the request, check the MIME type. When you send the response, set the right MIME type.

If the user-agent is using text/plain for everything, you're stuck with daxim's 'try it and see' method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜