From 72421fc4673e3aef58afe5d0a031cbd47711c6c8 Mon Sep 17 00:00:00 2001 From: Alessandro Ghedini Date: Thu, 2 Aug 2012 20:49:57 +0200 Subject: [PATCH] add IsValid::JSON goodie plugin --- lib/DDG/Goodie/IsValid/JSON.pm | 24 ++++++++++++++++++++++++ t/IsValid.t | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 lib/DDG/Goodie/IsValid/JSON.pm create mode 100755 t/IsValid.t diff --git a/lib/DDG/Goodie/IsValid/JSON.pm b/lib/DDG/Goodie/IsValid/JSON.pm new file mode 100644 index 000000000..ae384492b --- /dev/null +++ b/lib/DDG/Goodie/IsValid/JSON.pm @@ -0,0 +1,24 @@ +package DDG::Goodie::IsValid::JSON; + +use DDG::Goodie; + +use Try::Tiny; +use JSON qw(from_json); + +zci answer_type => 'isvalid'; +zci is_cached => 1; + +triggers start => 'is valid json', 'validate json'; + +handle remainder => sub { + my $result = try { + from_json($_); + return 'valid'; + } catch { + return 'invalid'; + }; + + return "Your JSON is $result!"; +}; + +1; diff --git a/t/IsValid.t b/t/IsValid.t new file mode 100755 index 000000000..db4ca5a5e --- /dev/null +++ b/t/IsValid.t @@ -0,0 +1,22 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +use Test::More; +use DDG::Test::Goodie; + +zci answer_type => 'isvalid'; +zci is_cached => 1; + +ddg_goodie_test( + [qw(DDG::Goodie::IsValid::JSON)], + 'is valid json {"test":"lol"}' => test_zci('Your JSON is valid!'), +); + +ddg_goodie_test( + [qw(DDG::Goodie::IsValid::JSON)], + 'is valid json {"test" "lol"}' => test_zci('Your JSON is invalid!'), +); + +done_testing;