如何在 Perl 中找到普通文本和 JSON 编码文本之间的区别? [英] How do I find the difference between normal text and the JSON encoded text in Perl?

查看:73
本文介绍了如何在 Perl 中找到普通文本和 JSON 编码文本之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中使用了 JSON::Any 在客户端和服务器.

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

我遇到了一个问题,我想找出文本(客户端发送的)是普通文本还是 JSON 编码文本.

I faced one problem, I want to find whether the text (sent by client) is normal text or JSON encoded text.

谁能告诉我怎么找,

没有检查,我在服务器端出错,它被关闭了.

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!

这篇关于如何在 Perl 中找到普通文本和 JSON 编码文本之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆