| 1 | #======================================================================== | ||
| 2 | # | ||
| 3 | # Badger::Codec::JSON | ||
| 4 | # | ||
| 5 | # DESCRIPTION | ||
| 6 | # Codec module for encoding/decoding Base64 | ||
| 7 | # | ||
| 8 | # AUTHOR | ||
| 9 | # Andy Wardley <abw@wardley.org> | ||
| 10 | # | ||
| 11 | #======================================================================== | ||
| 12 | |||
| 13 | package Badger::Codec::JSON; | ||
| 14 | |||
| 15 | use Badger::Class | ||
| 16 | version => 0.01, | ||
| 17 | base => 'Badger::Codec', | ||
| 18 | import => 'class CLASS', | ||
| 19 | codecs => 'utf8'; | ||
| 20 | |||
| 21 | our ($HAS_CP_JSON_XS, $HAS_JSON_XS, $HAS_JSON); | ||
| 22 | |||
| 23 | # Cpanel::JSON::XS is more complete/correct than JSON::XS | ||
| 24 | eval "require Cpanel::JSON::XS"; | ||
| 25 | $HAS_CP_JSON_XS = $@ ? 0 : 1; | ||
| 26 | |||
| 27 | # JSON::XS has bits missing (e.g. allow_bignum) | ||
| 28 | unless ($HAS_CP_JSON_XS) { | ||
| 29 | eval "require JSON::XS"; | ||
| 30 | $HAS_JSON_XS = $@ ? 0 : 1; | ||
| 31 | } | ||
| 32 | |||
| 33 | # fallback to Perl implementation | ||
| 34 | unless ($HAS_CP_JSON_XS || $HAS_JSON_XS) { | ||
| 35 | eval "require JSON"; | ||
| 36 | $HAS_JSON = $@ ? 0 : 1; | ||
| 37 | } | ||
| 38 | |||
| 39 | our $MODULE = | ||
| 40 | $HAS_CP_JSON_XS ? 'Cpanel::JSON::XS' : | ||
| 41 | $HAS_JSON_XS ? 'JSON::XS' : | ||
| 42 | $HAS_JSON ? 'JSON' : | ||
| 43 | CLASS->error("You don't have JSON, JSON::XS or Cpanel::JSON::XS installed"); | ||
| 44 | |||
| 45 | our $JSON = $MODULE->new; | ||
| 46 | |||
| 47 | sub encode_json { | ||
| 48 | $JSON->encode(shift); | ||
| 49 | } | ||
| 50 | |||
| 51 | sub decode_json { | ||
| 52 | my $json = shift; | ||
| 53 | # $json = encode_utf8($json); | ||
| 54 | $JSON->decode($json); | ||
| 55 | } | ||
| 56 | |||
| 57 | sub encode { | ||
| 58 | shift; | ||
| 59 | goto &encode_json; | ||
| 60 | } | ||
| 61 | |||
| 62 | sub decode { | ||
| 63 | shift; | ||
| 64 | goto &decode_json; | ||
| 65 | } | ||
| 66 | |||
| 67 | sub encoder { | ||
| 68 | \&encode_json; | ||
| 69 | } | ||
| 70 | |||
| 71 | sub decoder { | ||
| 72 | \&decode_json; | ||
| 73 | } | ||
| 74 | |||
| 75 | 1; | ||
| 76 | |||
| 77 | |||
| 78 | __END__ |