tags:

views:

53

answers:

2

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 normal 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.

+5  A: 

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!
daxim
Yeah. I tried this handling $SIG{__DIE__} signal even though I handle the signal, server killed. my main intention is to, server should not down for any reason.But your Idea is nice. I didn't think of another module.Thanks for your answer. And alternate Answers are always welcome.
sganesh
+1  A: 

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.

brian d foy
Actually, I didn't use any HTTP messages. I am using normal TCP socket program to transfer the messages ( hash is the data structure for that messages ).
sganesh
Maybe you should change that then. Meta data in your data transfers can tell the other side what it is getting.
brian d foy