JSONモジュールの encode_json / decode_json と to_json / from_json について調べてみた。
間違いがあった場合は指摘お願いします。
encode_json / decode_json
encode_json / decode_json は Encodeモジュールの encode_utf8 / decode_utf8 にJSONのシリアライザー・デシリアライザーがくっ付いたようなもの。
to_json / from_json
その一方、to_json / from_json は引数・戻り値共に flagged utf8 で扱う。JSONのシリアライザー・デシリアライザーのみ。
よって、エンコード周りに関しては自分で責任を持ってやる必要がある。
utf8(追記:コメントの指摘により加筆修正)
OOインターフェイスには utf8 メソッドがある。
引数が true もしくは「引数なし」では Enable となり、下記のようになる。 Disable にするには0(falseになる値)をセットする。
get_utf8 で現在の状態が確認できる。デフォルトはDisable
JSON->new->get_utf8 ? print "true" : print "false"; # false
encode_json と JSON->new->utf8->encode は同義
$json_text = encode_json $perl_scalar; $json_text = JSON->new->utf8->encode ($perl_scalar);
decode_json と JSON->new->utf8->decode ($json_text) は同義
$perl_scalar = decode_json $json_text; $perl_scalar = JSON->new->utf8->decode ($json_text);
to_json と JSON->new->encode は同義
$json_text = to_json($perl_scalar); $json_text = JSON->new->encode($perl_scalar);
from_json と JSON->decode は同義
$perl_scalar = from_json($json_text); $perl_scalar = JSON->decode($json_text);
サンプルコード
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use feature qw/say/;
use Encode;
use Data::Dumper;
use JSON;
my $v_1 = {
name => 'いろはにほへと',
value => 'ちりぬるを',
};
my $v_2 = {
name => 'わかよたれそ',
value => 'つねならむ',
};
my $v_3 = {
name => 'うゐのおくやま',
value => 'けふこへて',
};
$v_1->{name} = encode_utf8 $v_1->{name};
$v_1->{value} = encode_utf8 $v_1->{value};
say 'Wrong!!! ' . encode_json $v_1; # 多重エンコードしていることになる
say "Right: " . encode_json $v_2;
say "Right: " . encode_utf8 to_json($v_3);
my $to_json = to_json($v_3);
print Dumper "Right: ", from_json $to_json;
exit;
1;
__END__
# output
Wrong!!! {"value":"ちりぬるを","name":"いろはにほへと"}
Right: {"value":"つねならむ","name":"わかよたれそ"}
Right: {"value":"けふこへて","name":"うゐのおくやま"}
$VAR1 = 'Right: ';
$VAR2 = {
'value' => "\x{3051}\x{3075}\x{3053}\x{3078}\x{3066}",
'name' => "\x{3046}\x{3090}\x{306e}\x{304a}\x{304f}\x{3084}\x{307e}"
};
追記(2010.04.18)
あわせてこちらも
http://www.donzoko.net/cgi-bin/tdiary/20100406.html#p0
http://www.donzoko.net/cgi-bin/tdiary/20080329.html#p01