JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ
JSON::XS - JSON serialising/deserialising, done correctly and fast

目次 TABLE OF CONTENTS


名前 NAME

JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ JSON::XS - JSON serialising/deserialising, done correctly and fast

JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html)


概要 SYNOPSIS

 use JSON::XS;

 # exported functions, they croak on error
 # and expect/generate UTF-8
 # エクスポートされる関数, これらはエラー時には
 # corak し, UTF-8 を期待/生成します.

 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
 $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;

 # OO-interface

 $coder = JSON::XS->new->ascii->pretty->allow_nonref;
 $pretty_printed_unencoded = $coder->encode ($perl_scalar);
 $perl_scalar = $coder->decode ($unicode_json_text);

 # Note that JSON version 2.0 and above will automatically use JSON::XS
 # if available, at virtually no speed overhead either, so you should
 # be able to just:
 # JSON バージョン 2.0 以降は JSON::XS が利用可能だった場合それを
 # 自動的に使います, 仮想的には速度的なオーバーヘッドはないので,
 # 単に次のようにするこもができます:
 
 use JSON;

 # and do the same things, except that you have a pure-perl fallback now.
 # 後はさっきと同様, ただ今度はpure-perlでのフォールバックがついています.

訳注: VERSION 2.01 で to_json/from_json から encode_json/decode_json に 変更されました. 2.01 では古い関数はその旨のメッセージと共にcroakします. Translator's Note: On VERSION 2.01, to_json/from_json are renamed to encode_json/decode_json. Old ones are croaked with a message.


説明 DESCRIPTION

このモジュールは Perl データ構造の JSON への変換及びその逆処理を 行います. 第1の目標は 正しく あることであり, 第2は 高速 であることです. 後者の目標のために, C で記述しています. This module converts Perl data structures to JSON and vice versa. Its primary goal is to be correct and its secondary goal is to be fast. To reach the latter goal it was written in C.

バージョン 2.0 以降の JSON モジュールは, JSON と JSON::XS が 共にインストールされていた場合, JSON は JSON::XS (これは 上書きできます)へとエミュレーション(コンストラクタとメソッドの 継承による)のおかげでオーバーヘッドなしにフォールバックします. もし JSON::XS がなければバックエンドとして互換のある JSON::PP モジュールへとフォールバックするので, JSON::XS の代わりに JSON を使うことで, 必要であれば高速にもなれる, けれども C コンパイラを必要としないポータブルな JSON API を得ることができます. Beginning with version 2.0 of the JSON module, when both JSON and JSON::XS are installed, then JSON will fall back on JSON::XS (this can be overridden) with no overhead due to emulation (by inheriting constructor and methods). If JSON::XS is not available, it will fall back to the compatible JSON::PP module as backend, so using JSON instead of JSON::XS gives you a portable JSON API that can be fast when you need and doesn't require a C compiler when that is a problem.

このモジュールは CPAN で何番目かの JSON モジュールであり, なぜまた新しい JSON モジュールを作る必要があるのか疑問も あるでしょう. 多くの JSON モジュールはあるのですが, その いずれもきわどい部分での処理を正しく行えず, また多くの場合で そのメンテナが反応がなかったり, もはやいなかったり, 若しくは 他の理由でバグ報告を聞き入れてもらえなかったりなのです. As this is the n-th-something JSON module on CPAN, what was the reason to write yet another JSON module? While it seems there are many JSON modules, none of them correctly handle all corner cases, and in most cases their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons.

他の JSON モジュールとの比較に関しては, 後述の COMPARISON を 参照して下さい. See COMPARISON, below, for a comparison to some other JSON modules.

他の JSON モジュールとの比較は後述の COMPARISON を参照してください. See COMPARISON, below, for a comparison to some other JSON modules.

JSON::XS がどのように perl の値を JSON の値へと, そしてその逆を 対応づけているのかは後述の MAPPING を参照してください. See MAPPING, below, on how JSON::XS maps perl values to JSON values and vice versa.

機能 FEATURES

正しい Unicode 処理 * correct Unicode handling

このモジュールは Unicode の処理の仕方を知っていて, そしてそれをいつ どのようにして行うかについてを十分にドキュメント化して, さらには"正しさ"の内容をも記述しています. This module knows how to handle Unicode, documents how and when it does so, and even documents what "correct" means.

ラウンドトリップ完全性 * round-trip integrity

JSON がサポートしているデータタイプだけから成る perl データ構造を シリアライズした時, それをでシリアライズしたデータ構造は Perl レベルで同一となります (例えば文字列 "2.0" がいきなり "2" に 成ったりはしません, それは文字列であるので). これにはわずかな例外があるので, それに関しては 後述の MAPPING を読んでみてください. When you serialise a perl data structure using only data types supported by JSON, the deserialised data structure is identical on the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" just because it looks like a number). There minor are exceptions to this, read the MAPPING section below to learn about those.

JSON 正当性の厳密な確認 * strict checking of JSON correctness

デフォルトでは推測も不正な JSON 文字列の生成もしません, そして JSON はデフォルトでは入力としてだけ受け付けます (後者はセキュリティ的な機能です). There is no guessing, no generating of illegal JSON texts by default, and only JSON is accepted as input by default (the latter is a security feature).

高速 * fast

他の JSON モジュールや Storable といったシリアライザと比較して, このモジュールはスピードにおいてもおおよそ優位性を保っています. Compared to other JSON modules and other serialisers such as Storable, this module usually compares favourably in terms of speed, too.

簡単な使い方 * simple to use

このモジュールはオブジェクト指向インターフェースと同様にシンプルな 関数インターフェースを持っています. This module has both a simple functional interface as well as an object oriented interface.

合理的で万能な出力形式 * reasonably versatile output formats

1行形式が可能と保証する一番コンパクトな形式(簡単な行ベースの プロトコルに適切), pure-ASCII 形式(Unicode をサポートしつつも 8-bit クリーンでない転送に), 若しくはきれいに整形された 形式(それを読みたいときに)から選ぶことができます. さらにはこれらの 機能を好きなように組み合わせることもできます. You can choose between the most compact guaranteed-single-line format possible (nice for simple line-based protocols), a pure-ASCII format (for when your transport is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed format (for when you want to read that stuff). Or you can combine those features in whatever way you like.


関数インターフェース FUNCTIONAL INTERFACE

以下の便利なメソッドがモジュールから提供されています. これらはデフォルトでエクスポートされます. The following convenience methods are provided by this module. They are exported by default:

$json_text = encode_json $perl_scalar

与えられた Perl データ構造を UTF-8 エンコードされたバイナリ文字列 (つまり文字列にはオクテットのみが含まれる)へと変換します. エラー時には croak します. Converts the given Perl data structure to a UTF-8 encoded, binary string (that is, the string contains octets only). Croaks on error.

この関数は機能的には次のコードと同一です: This function call is functionally identical to:

   $json_text = JSON::XS->new->utf8->encode ($perl_scalar)

速くなることを除けば. Except being faster.

$perl_scalar = decode_json $json_text

encode_json の反対: UTF-8 (バイナリ)文字列であることと UTF-8 エンコードされた JSON テキストとしてパースを試みること, そして結果として得たリファレンスを返すこと除いて. エラー時には croak します. The opposite of encode_json: expects an UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. Croaks on error.

この関数は機能的には次のコードと同一です: This function call is functionally identical to:

   $perl_scalar = JSON::XS->new->utf8->decode ($json_text)

速くなることを除けば. Except being faster.

$is_boolean = JSON::XS::is_bool $scalar

渡されたスカラーが JSON::XS::true 若しくは JSON::XS::false を表現していれば真を返します, この2つの定数はそれぞれ 1 及び 0 のように振る舞い JSON の true 及び false の値を Perl で表現するために 使われます. Returns true if the passed scalar represents either JSON::XS::true or JSON::XS::false, two constants that act like 1 and 0, respectively and are used to represent JSON true and false values in Perl.

JSON での値がどのように Perl にマッピングされるかは, 後述の"マッピング" を参照してください. See MAPPING, below, for more information on how JSON values are mapped to Perl.


UNICODE と PERL に関する補足 A FEW NOTES ON UNICODE AND PERL

これはしばしば混乱のもととなっているので, バグを法として, Perlの中で Unicode がどのように動作しているか についていくつかはっきりさせておきます. Since this often leads to confusion, here are a few very clear words on how Unicode works in Perl, modulo bugs.

1. Perl の文字列には順序値>255となる文字を格納できる 1. Perl strings can store characters with ordinal values > 255.

これによって Unicode 文字を Perl 文字列において1文字として 格納することができます - とても自然ですね. This enables you to store Unicode characters as single characters in a Perl string - very natural.

2. Perl は文字列にエンコーディングを関連づけない 2. Perl does not associate an encoding with your strings.

... それを強制するのまでは. 例えば正規表現にマッチさせる, スカラーをファイルに出力するといったことを行った場合, Perl は文字列を設定に応じてロケールにエンコードされたテキスト, オクテット/バイナリ, 若しくはUnicodeとして処理されます. データと一緒にエンコーディングが記録されることはありません, エンコーディングを決定するのは不思議なメタデータなどではなく 使い方です. ... until you force it to, e.g. when matching it against a regex, or printing the scalar to a file, in which case Perl either interprets your string as locale-encoded text, octets/binary, or as Unicode, depending on various settings. In no case is an encoding stored together with your data, it is use that decides encoding, not any magical meta data.

3. 内部の utf-8 フラグは文字列に対してエンコーディングを 考慮しているかを示している訳ではない 3. The internal utf-8 flag has no meaning with regards to the encoding of your string.

Perl のバグ若しくは XS で書かれたモジュールをデバッグしている, 若しくは perl の内部に飛び込みたいのいずれでもないのなら, このフラグは無視してください. それらの時以外は混乱するだけです, その名前にも関わらず, 文字列がエンコードされているかを全く伝えません. このフラグが設定されていてもいなくとも Unicode 文字列を持つことはでき, このフラグが設定されていてもいなくともバイナリデータを持つことができます. その他の可能性もあります. Just ignore that flag unless you debug a Perl bug, a module written in XS or want to dive into the internals of perl. Otherwise it will only confuse you, as, despite the name, it says nothing about how your string is encoded. You can have Unicode strings with that flag set, with that flag clear, and you can have binary data with that flag set and that flag clear. Other possibilities exist, too.

もしこのフラグについて知らないのであれば, それはよいことであり, それが存在しないかのように振る舞っていてください. If you didn't know about that flag, just the better, pretend it doesn't exist.

4. "Unicode文字列"は単に個々の文字をUnicodeコードポイントとして 正常に処理できる文字列です. 4. A "Unicode String" is simply a string where each character can be validly interpreted as a Unicode code point.

もし UTF-8 エンコードされたデータを持っているのなら, それはもはや Unicode 文字列ではなく, バイナリ文字列を提供提供している UTF-8 でエンコードされた Unicode 文字列です. If you have UTF-8 encoded data, it is no longer a Unicode string, but a Unicode string encoded in UTF-8, giving you a binary string.

_255)_character_values_is_not_a_UTF-8_string.">5. "大きな" (> 255)文字値を含んだ文字列は UTF-8 文字列ではありません. 5. A string containing "high" (> 255) character values is not a UTF-8 string.

事実です. 受け入れてください. It's a fact. Learn to live with it.

一助になれば幸いです :) I hope this helps :)


オブジェクト指向インターフェース OBJECT-ORIENTED INTERFACE

オブジェクト指向インターフェースを使うことで好きなエンコード及び デコード形式をサポートされている中でではありますが選ぶことが できます. The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats.

$json = new JSON::XS

JSON 文字列絵をデコード/エンコードするための新しい JSON::XS オブジェクトを生成します. 以下で説明されている全ての真偽フラグは デフォルトでは 無効 になっています. Creates a new JSON::XS object that can be used to de/encode JSON strings. All boolean flags described below are by default disabled.

フラグの変更を行うメソッドは全て JSON オブジェクトを再び返すので 呼び出しは連続して行えます: The mutators for flags all return the JSON object again and thus calls can be chained:

   my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
   => {"a": [1, 2]}
$json = $json->ascii ([$enable])
$enabled = $json->get_ascii

$enable が真の時(若しくは省略された時), encode メソッドは 0..127 (つまりASCII) 以外の範囲の文字を生成しなくなります. この範囲にない全ての Unicode 文字は RFC 4627 にあるように \uXXXX (BMP文字)か2つの \uHHHH\uLLLL エスケープシーケンスで 表現されます. エンコードされた JSON テキストの結果は ネイティブなUnicode文字列, ascii-エンコード, latin1-エンコード 若しくは UTF-8 エンコードされた文字列, 若しくはそれ以外の ASCII の スーパーセットとして扱うことが出来ます. If $enable is true (or missing), then the encode method will not generate characters outside the code range 0..127 (which is ASCII). Any Unicode characters outside that range will be escaped using either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. The resulting encoded JSON text can be treated as a native Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, or any other superset of ASCII.

$enable が偽であれば, encode メソッドは JSON 構文若しくは 他のフラグによって 必要とされているのでなければ Unicode 文字をエスケープしません. これによってフォーマットが高速でコンパクトになります. If $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format.

このドキュメントの後の方に出てくる ENCODING/CODESET FLAG NOTES も参照してください. See also the section ENCODING/CODESET FLAG NOTES later in this document.

このフラグは主にエンコードされた JSON テキストが 8 bit 文字を 全く含めることが出来ない 7-bit 経路を通して転送するために 使います. The main use for this flag is to produce JSON texts that can be transmitted over a 7-bit channel, as the encoded JSON texts will not contain any 8 bit characters.

  JSON::XS->new->ascii (1)->encode ([chr 0x10401])
  => ["\ud801\udc01"]
$json = $json->latin1 ([$enable])
$enabled = $json->get_latin1

$enable が真の時(若しくは省略された時), encode メソッドは 0..255 の範囲にない全ての文字をエスケープして, JSON テキストを latin1 (若しくは iso-8859-1)として エンコードします. 結果として得られる文字列は latin1-エンコードされた JSON テキスト若しくはネイティブなUnicode文字列として扱うことが できます. decode メソッドはこのフラグでは何も影響を起こしません, decode は厳密に latin1 のスーパーセットであるUnicodeを デフォルトで想定しているためです. If $enable is true (or missing), then the encode method will encode the resulting JSON text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255. The resulting string can be treated as a latin1-encoded JSON text or a native Unicode string. The decode method will not be affected in any way by this flag, as decode by default expects Unicode, which is a strict superset of latin1.

$enable が偽であれば, encode メソッドは JSON 構文若しくは 他のフラグで必要とされなければ Unicode 文字をエスケープしません. If $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags.

このドキュメントの後の方に出てくる ENCODING/CODESET FLAG NOTES も参照してください. See also the section ENCODING/CODESET FLAG NOTES later in this document.

このフラグは主にバイナリデータを JSON テキストとして効率的に, 多くのオクテットをエンスケープせず, サイズをあまり増やさずに エンコードすることを目的としています. 欠点として結果として 得られる JSON テキストは latin1 でエンコードされていて (そして格納や転送は適切に行われなければなりません), これは JSON のエンコードではあまり使われていません. けれどもこれは他の JSON エンコーダ/デコーダとやりとりする時ではなく, ファイルやデータベースに効率的にバイナリデータを含めるために知られている データ構造を格納したい時にとても役立ちます. The main use for this flag is efficiently encoding binary data as JSON text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting JSON text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for JSON. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders.

  JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
  => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
$json = $json->utf8 ([$enable])
$enabled = $json->get_utf8

$enable が真の時(若しくは省略された時), encode メソッドは 多くのプロトコルが要求するように JSON 文字列を UTF-8 へと エンコードし, decode メソッドは UTF-8 エンコードされた文字列を 処理するようになります. UTF-8 文字列には 0..255 の範囲外の文字を 含まないことに注意してください, これはバイト/バイナリ I/O に 役立ちます. 今後のバージョンではこのオプションを有効にすることで RFC 4627 に書かれているように UTF-16 及び UTF-32 エンコーディング ファミリを自動認識するようになるかもしれません. If $enable is true (or missing), then the encode method will encode the JSON result into UTF-8, as required by many protocols, while the decode method expects to be handled an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range 0..255, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627.

$enable が偽の時には encode メソッドは (エンコードされていない) Unicode 文字列として JSON 文字列を返し, decode は Unicode 文字列を 処理するようになります. デコーディング若しくはエンコーディング (つまり UTF-8 若しくは UTF-16)は自分で行う必要があります, つまり Encode モジュールを使って. If $enable is false, then the encode method will return the JSON string as a (non-encoded) Unicode string, while decode expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.

このドキュメントの後の方に出てくる ENCODING/CODESET FLAG NOTES も参照してください. See also the section ENCODING/CODESET FLAG NOTES later in this document.

例, UTF-16BE でエンコードされた JSON を出力: Example, output UTF-16BE-encoded JSON:

  use Encode;
  $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);

例, UTF-32LE でエンコードされた JSON のデコード: Example, decode UTF-32LE-encoded JSON:

  use Encode;
  $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
$json = $json->pretty ([$enable])

このメソッドは indent, space_before, そして space_after のフラグの全てを一度の呼び出しで一番読みやすい(若しくはコンパクトな) 形式の生成に有効に(若しくは無効に)します. This enables (or disables) all of the indent, space_before and space_after (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible.

例, シンプルな構造をきれいに出力: Example, pretty-print some simple structure:

   my $json = JSON::XS->new->pretty(1)->encode ({a => [1,2]})
   =>
   {
      "a" : [
         1,
         2
      ]
   }
$json = $json->indent ([$enable])
$enabled = $json->get_indent

$enable が真の時(若しくは省略された時), encode メソッドは 出力に複数行の形式をつかって全ての配列メンバやオブジェクト/ハッシュの キー-値ペアをそれぞれ独立した行に適切に区別して配置するように なります. If $enable is true (or missing), then the encode method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly.

$enable が偽の時, 改行やインデントは生成されなくなり, 返される JSON テキストは newline を含んでいないことが 保証されます. If $enable is false, no newlines or indenting will be produced, and the resulting JSON text is guaranteed not to contain any newlines.

この設定は JSON テキストのデコードには影響しません. This setting has no effect when decoding JSON texts.

$json = $json->space_before ([$enable])
$enabled = $json->get_space_before

$enable が真の時(若しくは省略された時), encode メソッドは JSON オブジェクトで キーと値を隔てている : の前に空白を 入れるようになります. If $enable is true (or missing), then the encode method will add an extra optional space before the : separating keys from values in JSON objects.

$enable が偽の時, encode メソッドはそこに余計な空白を いれなくなります. If $enable is false, then the encode method will not add any extra space at those places.

この設定は JSON テキストのデコードには影響しません. この設定はたいてい space_after と一緒に使われるでしょう. This setting has no effect when decoding JSON texts. You will also most likely combine this setting with space_after.

例, space_before が有効で space_after と indent を無効にした時: Example, space_before enabled, space_after and indent disabled:

   {"key" :"value"}
$json = $json->space_after ([$enable])
$enabled = $json->get_space_after

$enable が真の時(若しくは省略された時), encode メソッドは JSON オブジェクトでキーと値を隔てている : の後ろと, キー-値ペアや配列メンバの間にある , の後に空白を入れるように なります. If $enable is true (or missing), then the encode method will add an extra optional space after the : separating keys from values in JSON objects and extra whitespace after the , separating key-value pairs and array members.

$enable が偽の時, encode メソッドはそこに余計な空白を いれなくなります. If $enable is false, then the encode method will not add any extra space at those places.

この設定は JSON テキストのデコードには影響しません. This setting has no effect when decoding JSON texts.

例, space_before と indent が無効で space_after を有効にした時: Example, space_before and indent disabled, space_after enabled:

   {"key": "value"}
$json = $json->relaxed ([$enable])
$enabled = $json->get_relaxed

$enable が真の時(若しくは省略された時), decode メソッドは 通常の JSON 構文に対する幾つかの拡張(後述)を受け付けるようになります. encode には何も影響しません. このオプションを使うと正規でない JSONテキストを正規であるかのように受け付けるようになります! このオプションはアプリケーションに特化した人の読めるファイル (設定ファイル, リソースファイルなど)をパースするときにのみ使うべきでしょう. If $enable is true (or missing), then decode will accept some extensions to normal JSON syntax (see below). encode will not be affected in anyway. Be aware that this option makes you accept invalid JSON texts as if they were valid!. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)

$enable が偽の時(デフォルト), decode は有効なJSONテキストのみを 受理するようになります. If $enable is false (the default), then decode will only accept valid JSON texts.

現状受理される拡張は以下の通り: Currently accepted extensions are:

* リスト要素の末尾のコンマ * list items can have an end-comma

JSON は配列の要素やキー-値ペアをコンマで区切ります. これはJSONテキストを手で書いていて要素を簡単に追加できるようにしたい 時には非常に煩わしくなります, そこでこの拡張ではそれらの間ではなく 終わりにあるコンマも受け付けます: JSON separates array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them:

   [
      1,
      2, <- this comma not normally allowed
   ]
   {
      "k1": "v1",
      "k2": "v2", <- this comma not normally allowed
   }
* shell-スタイルの '#'-コメント * shell-style '#'-comments

JSON が白空白を受け付ける箇所において, shell-スタイルのコメントも 追加で受理します. これは最初の復帰(carriage-return) 若しくは行末(line-feed)文字で終わり, その後にさらに白空白やコメントを 受け付けます. Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed.

  [
     1, # this comment not allowed in JSON
        # neither this one...
  ]
$json = $json->canonical ([$enable])
$enabled = $json->get_canonical

$enable が真の時(若しくは省略された時), encode メソッドは キーをソートした形で JSON オブジェクトを出力ようになります. これは幾分大きめのオーバーヘッドになります. If $enable is true (or missing), then the encode method will output JSON objects by sorting their keys. This is adding a comparatively high overhead.

$enable が偽の時, encode メソッドはキー-値ペアを Perl が 格納している順番に出力するようになります(同じスクリプトでも 実行するたびに変化するでしょう). If $enable is false, then the encode method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script).

このオプションは同じデータ構造からは(そして同じ設定であれば) 同一の JSON テキストにエンコードしたい時に役に立つでしょう. これが無効になっているときには同じハッシュで同じデータを 含んでいても Perl ではキー-値ペアは順序を継承しないため 異なった文字列へとエンコードされるでしょう. This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl.

この設定は JSON テキストのデコードには影響しません. This setting has no effect when decoding JSON texts.

$json = $json->allow_nonref ([$enable])
$enabled = $json->get_allow_nonref

$enable が真の時(若しくは省略された時), encode メソッドは リファレンスではない値を適切な文字列, 数値, 若しくは null の JSON 値へと変換します, これは RFC 4627 に対する拡張です. decode はそのような JSON 値を croak するのではなく 受け入れるようになります. If $enable is true (or missing), then the encode method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, decode will accept those JSON values instead of croaking.

$enable が偽の時, encode メソッドは JSON テキストはオブジェクトか 配列でなければならず, 配列リファレンスでもハッシュ リファレンスでもないものが渡されたときには例外を投げるようになります. 同じように, decode は JSON オブジェクトか配列ではない何かが 与えられたときには croak するようになります. If $enable is false, then the encode method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, decode will croak if given something that is not a JSON object or array.

例, Perl スカラーを allow_nonref を有効にして JSON 値へと エンコードすると無効な JSON テキストを生成します: Example, encode a Perl scalar as JSON value with enabled allow_nonref, resulting in an invalid JSON text:

   JSON::XS->new->allow_nonref->encode ("Hello, World!")
   => "Hello, World!"
$json = $json->allow_unknown ([$enable])
$enabled = $json->get_allow_unknown

$enable が真の時(若しくは省略された時), encode メソッドは JSON で表現できない値(例えばファイルハンドル)に遭遇したときに 例外を投げなくなり, その代わりに JSON の null 値へと エンコードするようになります. ブレスされたオブジェクトはこの設定には含まれず, それらは allow_nonref で別に処理されます. If $enable is true (or missing), then encode will not throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON null value. Note that blessed objects are not included here and are handled separately by allow_nonref.

$enable が偽の時(デフォルト), encode メソッドは JSON としてエンコードできない何かを見つけると 例外を投げます. If $enable is false (the default), then encode will throw an exception when it encounters anything it cannot encode as JSON.

このオプションは decode には全く影響しません, また, 通信相手を知っている場合以外では無効にしておくことを 推奨します. This option does not affect decode in any way, and it is recommended to leave it off unless you know your communications partner.

$json = $json->allow_blessed ([$enable])
$enabled = $json->get_allow_blessed

$enable が真の時(若しくは省略された時), encode メソッドが ブレスされたリファレンスに遭遇したとき嘔吐しなくなります. 代わりに, convert_blessed オプションの値によって null (convert_blessed 無効若しくは TO_JSON メソッドが 見つからなかった)若しくはオブジェクトの表現(convert_blessed が 有効で TO_JSON メソッドが見つかった)のどちらにエンコード されるかが決まります. decode には影響しません. If $enable is true (or missing), then the encode method will not barf when it encounters a blessed reference. Instead, the value of the convert_blessed option will decide whether null (convert_blessed disabled or no TO_JSON method found) or a representation of the object (convert_blessed enabled and TO_JSON method found) is being encoded. Has no effect on decode.

$enable が偽のとき(デフォルト)は, encode は ブレスされたオブジェクトに遭遇した時は例外を投げます. If $enable is false (the default), then encode will throw an exception when it encounters a blessed object.

$json = $json->convert_blessed ([$enable])
$enabled = $json->get_convert_blessed

$enable が真の時(若しくは省略された時), encode メソッドは ブレスされたオブジェクトと東宮した時にオブジェクトのクラスに TO_JSON メソッドが有効かどうかを調べます. もし見つかれば, それはスカラーコンテキストで呼ばれ, その復帰値のスカラーが オブジェクトの代わりにエンコードされます. もし TO_JSON メソッドが見つからなければ, allow_blessed の値で どうするかが変わります. If $enable is true (or missing), then encode, upon encountering a blessed object, will check for the availability of the TO_JSON method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object. If no TO_JSON method is found, the value of allow_blessed will decide what to do.

TO_JSON メソッドでは必要であれば die を安全に呼び出すことが できます. もし TO_JSON が別のブレスされているオブジェクトを 返したのであれば, それは同じように処理されます. TO_JSON は この時に終わらない無限再帰(==クラッシュ)を起こさないように 気をつけなければなりません. TO_JSON の名前は Perl コアによって 呼ばれる他のメソッド(==オブジェクトの使用者によってではなく)は 大抵大文字であることと, to_json 関数との衝突を回避するために 選ばれました. The TO_JSON method may safely call die if it wants. If TO_JSON returns other blessed objects, those will be handled in the same way. TO_JSON must take care of not causing an endless recursion cycle (== crash) in this case. The name of TO_JSON was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with any to_json function or method.

この設定は流暢な decode というわけではまだありませんが, 将来的には, 流暢に decode できてこの設定によって有効にできる グローバルフックがインストールされるでしょう. This setting does not yet influence decode in any way, but in the future, global hooks might get installed that influence decode and are enabled by this setting.

$enable が偽であったときには, ブレスされたオブジェクトが 見つかったときに何を行うかは allow_blessed 設定で 決定されます. If $enable is false, then the allow_blessed setting will decide what to do when a blessed object is found.

$json = $json->filter_json_object ([$coderef->($hashref)])

$coderef が指定されたときには, JSON オブジェクトをデコードするたびに decode から呼び出されます. この時の唯一の引数は新しく作られた ハッシュへのリファレンスです. もしコードリファレンスが 単一のスカラー(リファレンスである必要はありません)を返すと, この値(つまりエイリアスを回避するためにこのスカラーのコピー)は デシリアライズされるデータ構造に挿入されます. もし空のリスト (補足: 有効なスカラーである undef ではありません)が 返されると, 元のデシリアライズされたオブジェクトが挿入されます. この設定はデコードをかなり遅くさせます. When $coderef is specified, it will be called from decode each time it decodes a JSON object. The only argument is a reference to the newly-created hash. If the code references returns a single scalar (which need not be a reference), this value (i.e. a copy of that scalar to avoid aliasing) is inserted into the deserialised data structure. If it returns an empty list (NOTE: not undef, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably.

$coderef が省略されたとき若しくは未定義だったときには, 既存のコールバックは削除され, decode はデシリアライズされた ハッシュを全く変更しなくなります. When $coderef is omitted or undefined, any existing callback will be removed and decode will not change the deserialised hash in any way.

全ての JSON オブジェクトを整数 5 へと変換する例: Example, convert all JSON objects into the integer 5:

   my $js = JSON::XS->new->filter_json_object (sub { 5 });
   # returns [5]
   $js->decode ('[{}]')
   # throw an exception because allow_nonref is not enabled
   # so a lone 5 is not allowed.
   $js->decode ('{"a":1, "b":2}');
$json = $json->filter_json_single_key_object ($key [=> $coderef->($value)])

かすかに filter_json_object のようにも動作しますが, $key という名前のキーを1つもっている JSON オブジェクトに 対してのみ呼び出されます. Works remotely similar to filter_json_object, but is only called for JSON objects having a single key named $key.

この $codereffilter_json_object を通して指定される前に 呼び出されます. これには JSON オブジェクトのその1つの値が 渡されます. もしそれが1つの値を返すと, それがデータ構造に挿入されます. もしそれが何も返さなければ(やはり空のリストではなく undef だったとき ではありません), 単一キーコールバックが指定されなかったかのように 続けて filter_json_object のコールバックが呼び出されます. This $coderef is called before the one specified via filter_json_object, if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even undef but the empty list), the callback from filter_json_object will be called next, as if no single-key callback were specified.

$coderef が省略されたとき若しくは未定義だったときには, 対応するコールバックは無効にされます. 与えられたキーに対して 1つのコールバックのみが存在できます. If $coderef is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key.

このコールバックは filter_json_object よりも呼び出される回数が少ないので, デコードの速度はそんなには影響しないでしょう. そのために 単一キーオブジェクトは Perl オブジェクトを優秀にシリアライズ できるでしょう, 特に単一キーの JSON オブジェクトはタイプタグのついた 値というコンセプトと同じくらい類似したものを JSON として得ます (これは基本的にID/VALUEの組). もちろん, JSON がこれをサポートしてる のではないのでシリアライズされた Perl ハッシュのようにも見える この構造を使わないようにする必要があります. As this callback gets called less often then the filter_json_object one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialise Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash.

この単一オブジェクトのための典型的なキーの名前としては, 実際のハッシュと衝突しないように __class_whatever__ 若しくは $__dollars_are_rarely_used__$ 若しくは }ugly_brace_placement, 若しくは __class_md5sum(classname)__ といった ものがよいでしょう. Typical names for the single object key are __class_whatever__, or $__dollars_are_rarely_used__$ or }ugly_brace_placement, or even things like __class_md5sum(classname)__, to reduce the risk of clashing with real hashes.

{ "__widget__" => <id> } の形式の JSON オブジェクトを 対応する $WIDGET{<id>} オブジェクトへとデコードする例: Example, decode JSON objects of the form { "__widget__" => <id> } into the corresponding $WIDGET{<id>} object:

   # return whatever is in $WIDGET{5}:
   # $WIDGET{5} にある何かを返す:
   JSON::XS
      ->new
      ->filter_json_single_key_object (__widget__ => sub {
            $WIDGET{ $_[0] }
         })
      ->decode ('{"__widget__": 5')

   # this can be used with a TO_JSON method in some "widget" class
   # for serialisation to json:
   # これは何らかの"widget"クラスでjsonへとシリアライズする為の
   # TO_JSON でも使うことが出来ます.
   sub WidgetBase::TO_JSON {
      my ($self) = @_;

      unless ($self->{id}) {
         $self->{id} = ..get..some..id..;
         $WIDGET{$self->{id}} = $self;
      }

      { __widget__ => $self->{id} }
   }
$json = $json->shrink ([$enable])
$enabled = $json->get_shrink

Perl は文字列用のスペースを確保する時に通常わずかに多めのメモリを 確保します. この省略可能なフラグは encode 若しくは decode が生成する文字列を出来る限り小さくリサイズします. これは JSON テキストが とてもとても長くなったり短い文字列がたくさん出来たときにメモリ消費を 押さえることが出来ます. これは可能であれば文字列をオクテット形式へと 変換することも試みます: perl は内部的に文字列を UTF-X かオクテット 形式のどちらかのエンコーディングで格納します. 後者は全てを 格納できるわけではありませんが一般的に少ないメモリしか使いません (そして幾つかのバグリ気味な Perl や C のコードは使われている内部表現に 依存しているかもしれません). Perl usually over-allocates memory a bit when allocating space for strings. This flag optionally resizes strings generated by either encode or decode to their minimum size possible. This can save memory when your JSON texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less space in general (and some buggy Perl or C code might even rely on that internal representation being used).

shrink が行うことの実際の定義は今後のバージョンで変わるかもしれませんが, 常に時間と引き換えに使用している空間の削減を行います. The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time.

$enable が真の時(若しくは省略された時), encode メソッドから 返される文字列はぴったり合うように shrink され, そして decode が生成する全ての文字列もまた shrink されています. If $enable is true (or missing), the string returned by encode will be shrunk-to-fit, while all strings generated by decode will also be shrunk-to-fit.

$enable が偽の時は, 通常の perl でのメモリ確保アルゴリズムが使われます. あなたのデータを使って作業しているのなら, これは速くなるでしょう. If $enable is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster.

今後, この設定は空間を節約するために他のこと, 例えば整数や小数っぽい 文字列は内部的に数値や小数に変換する(これらは Perl レベルでは違いは ありません)といったことも行うようになるかもしれません. In the future, this setting might control other things, such as converting strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space.

$json = $json->max_depth ([$maximum_nesting_depth])
$max_depth = $json->get_max_depth

エンコードやデコード時に許可する最大のネストレベルを設定します( デフォルトは 512 です). もし JSON テキストか Perl データ構造に おいてより大きなネストレベルが検出されると, エンコーダ及び デコーダは停止してその時点で coark します. Sets the maximum nesting level (default 512) accepted while encoding or decoding. If a higher nesting level is detected in JSON text or a Perl data structure, then the encoder and decoder will stop and croak at that point.

ネストレベルはその地点にたどり着くまでにエンコーダが巡回する必要が あったハッシュや配列リファレンスの数若しくは文字列中で 与えられた文字にたどり着くまでに横切った { 若しくは [ 文字のうち閉じ括弧と対応していないものの数と定義しています. Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of { or [ characters without their matching closing parenthesis crossed to reach a given character in a string.

最大深度を1に設定すると一切のネストを許さなくなり, これは オブジェクトがただ1つのハッシュ/オブジェクト若しくは配列のみで あることを保証します. Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array.

引数が与えられなかった場合, とりうる最大の設定がつかわれますが, これが役に立つのは稀なことでしょう. If no argument is given, the highest possible setting will be used, which is rarely useful.

ネストは C の再帰で実装されています. デフォルト値は 一般的なオペレーティングシステムでクラッシュしない程度の 大きさを選んでいます. Note that nesting is implemented by recursion in C. The default value has been chosen to be as large as typical operating systems allow without crashing.

これがなぜ便利なのかの詳しい情報は SECURITY CONSIDERATIONS を 参照してください. See SECURITY CONSIDERATIONS, below, for more info on why this is useful.

$json = $json->max_size ([$maximum_string_size])
$max_size = $json->get_max_size

デコードが行われようとしたときに JSON テキストの持つことのできる 最大長を(バイトで)設定します. デフォルトは制限を行わないことを意味する 0 です. decode がこのバイト数を超える長さの文字列に対して 呼び出されたときはその文字列のデコードを行うのではなく例外を発生させます. この設定は encode には(今のところ)影響しません. Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is 0, meaning no limit. When decode is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on encode (yet).

引数が与えられなかったときには, 制限チェックは無効にされます (0を指定されたときと同じです). If no argument is given, the limit check will be deactivated (same as when 0 is specified).

これがなぜ便利なのかの詳しい情報は SECURITY CONSIDERATIONS を 参照してください. See SECURITY CONSIDERATIONS, below, for more info on why this is useful.

$json_text = $json->encode ($perl_scalar)

与えられた Perl データ構造(単純なスカラ若しくはハッシュか配列への リファレンス)をその JSON 表現へと変換します. 単純なスカラは JSON 文字列か数値シーケンスへと変換され, 配列へのリファレンスは JSON 配列になり, ハッシュへのリファレンスは JSON オブジェクトと なります. Perl の未定義値 (例えば undef)は JSON の null 値に なります. true 若しくは false の値も生成されるでしょう. Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its JSON representation. Simple scalars will be converted into JSON string or number sequences, while references to arrays become JSON arrays and references to hashes become JSON objects. Undefined Perl values (e.g. undef) become JSON null values. Neither true nor false values will be generated.

$perl_scalar = $json->decode ($json_text)

encode の反対です: JSON テキストを受け取ってそのパースを試し, 取り出した単純なスカラかリファレンスを返します. エラー時には croak します. The opposite of encode: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error.

JSON の数字と文字列は単純な Perl スカラーになります. JSON の配列は Perl の配列リファレンスとなり JSON オブジェクトは Perl ハッシュリファレンスになります. true1 に, false0 に, そして nullundef になります. JSON numbers and strings become simple Perl scalars. JSON arrays become Perl arrayrefs and JSON objects become Perl hashrefs. true becomes 1, false becomes 0 and null becomes undef.

($perl_scalar, $characters) = $json->decode_prefix ($json_text)

これは decode メソッドのように動作しますが, 最初の JSON オブジェクトの後でゴミを引きずっているときに例外を 発生させる代わりに静かにそこでパースを停止してそこまでに消費した 文字数を返します. This works like the decode method, but instead of raising an exception when there is trailing garbage after the first JSON object, it will silently stop parsing there and return the number of characters consumed so far.

これは JSON テキストが(その最初の場所で一番輝いてるのではなくて) 別のプロトコルで区切られていないけれど JSON テキストの終わる場所を知る必要があるときに便利です. This is useful if your JSON texts are not delimited by an outer protocol (which is not the brightest thing to do in the first place) and you need to know where the JSON text ends.

   JSON::XS->new->decode_prefix ("[1] the tail")
   => ([], 3)

少しずつのパース INCREMENTAL PARSING

いくつかのケースにおいて, JSON テキストを少しずつ(インクリメンタルに) パースすることが必要な場面もあるでしょう. このモジュールは常に JSON テキストとそこから得られた Perl データ構造を メモリに同時に保持しているので, JSON ストリームを少しずつパースすることも 可能です. これは JSON オブジェクト全体が得られるまで, デコードできる テキストになるまで蓄積することにとって実現しています. この処理は完全な JSON オブジェクトが提供されているのなら decode_prefix を使った場合と似たような感じになります, しかしもっとより効率的です (そして最小限のメソッド呼び出しで実装されています). In some cases, there is the need for incremental parsing of JSON texts. While this module always has to keep both JSON text and resulting Perl data structure in memory at one time, it does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to using decode_prefix to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls).

JSON::XS は本当に単純な, けれども 真にインクリメンタルなパーサーを使って, JSON テキストを一度のみ 結果を決定定期に得るのに十分な分のみをパースします). これは完全なパーサでは早すぎて止めれないことを意味します, 例えば, 括弧の不一致を検出できません. これが唯一保証することは, 構文的に正しい JSON テキストがあれば それをすぐにデコードを開始することのみです. これは構文エラーの時にパーサがその場でパースを停止するように保証するために リソース制限(例えばmax_size)を設定する必要があることを意味します. JSON::XS will only attempt to parse the JSON text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won't stop as early as the full parser, for example, it doesn't detect parenthese mismatches. The only thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. This means you need to set resource limits (e.g. max_size) to ensure the parser will stop parsing in the presence if syntax errors.

インクリメンタルパーサは以下のメソッドで実現されています. The following methods implement this incremental parser.

[void, scalar or list context] = $json->incr_parse ([$string])

これがパース関数の中心です. 新しいテキストを追加することもこれまでに蓄積されたストリームから オブジェクトを取り出すこともできます(この機能はどちらも任意です). This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional).

$string が与えられたときには, $json オブジェクトに保存されている JSON の断片にその文字列を 追加します. If $string is given, then this string is appended to the already existing JSON fragment stored in the $json object.

その後, 関数が void コンテキストで呼ばれていればそれ以上はなにも しないで帰ります. この機能によって必要なだけ断片となっている テキストを追加していくことができます. After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want.

メソッドがスカラーコンテキストで呼び出されていた場合には, JSON オブジェクトを1つだけ取り出そうとしてみます. もしそれが出来ればそのオブジェクトを返し, それが出来なければ undef を返します. もしパースエラーが あれば, このメソッドは decode と同じように croak します (エラーとなった箇所を飛ばすためには incr_skip を使います). これがこの関数のよくあるな使い方でしょう. If the method is called in scalar context, then it will try to extract exactly one JSON object. If that is successful, it will return this object, otherwise it will return undef. If there is a parse error, this method will croak just as decode would do (one can then use incr_skip to skip the errornous part). This is the most common way of using the method.

そして最後に, リストコンテキストだった場合には, ストリームから複数のオブジェクトを取り出して返そうとします, もしくは取り出せなければ空のリストを返します. これが動作するためには JSON オブジェクト若しくは配列が 区切りなしに連続して結合していなければなりません. もしエラーが起きた場合には, スカラーコンテキストの場合と同様に 例外が発生します. この時それまでにパースされた JSON テキストは 失われる点に注意してください. And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators between the JSON objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed JSON texts will be lost.

$lvalue_string = $json->incr_text

このメソッドは現在保存されている JSON の断片を lvalue として返します, つまりこれを処理することも出来ます. これはそれまでに incr_parseスカラーコンテキストで 正常にオブジェクトを返した後でのみ正常に動作します. それ以外の状況ではこの関数を呼び出しではいけません (と私は思います. 簡単なテストでは実際に動きますが, 実運用の環境では失敗となるでしょう). 特殊な例外として, 何かをパースさせる前にこのメソッドを 呼ぶことが出来ます. This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This only works when a preceding call to incr_parse in scalar context successfully returned an object. Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it will fail under real world conditions). As a special exception, you can also call this method before having parsed anything.

この関数は2つのケースで役に立ちます: a) JSON オブジェクトの後に残っているテキストを見つけるとき 若しくは b) JSON テキスト以外(例えばコンマ)で区切られている 複数の JSON オブジェクトをパーすするとき. This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas).

$json->incr_skip

これはインクリメンタルパースの状態をリセットし, 入力バッファからパースされたテキストを取り除きます. これは incr_parse が die した時に, その時はまだ入力バッファと内部状態がそのまま残っているので, それまでにパースされたテキストをスキップして, パース状態をリセットするのに 役に立ちます. This will reset the state of the incremental parser and will remove the parsed text from the input buffer. This is useful after incr_parse died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state.

$json->incr_reset

これはインクリメンタルパースを完全にリセットします, つまり, これを呼び出した後は, パーサはあたかも何もパースしていないかのような 状態になります. This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything.

これは JSON オブジェクトを繰り返しパースしたいけれど 後ろにくっついているデータは無視したい, つまりデコードの後に パーサをリセットする必要があるときに役に立ちます. This is useful if you want ot repeatedly parse JSON objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode.

制限 LIMITATIONS

デコードに作用する全てのオプションは allow_nonref 以外 サポートされています. これは動作が明白に鳴らないためです: JSON オブジェクト及び配列は それ自身で区切られています, つまり, オブジェクトをぴったりくっつけても それらは完璧にデコード可能です. とは行ってもこれは JSON 数値においてはその限りではありません. All options that affect decoding are supported, except allow_nonref. The reason for this is that it cannot be made to work sensibly: JSON objects and arrays are self-delimited, i.e. you can concatenate them back to back and still decode them perfectly. This does not hold true for JSON numbers, however.

例えば, 文字列 1 は単一の独立した JSON 数値でしょうか, それとも 12 の最初の部分でしょうか? では 12 が単一の独立した JSON 数値でしょうか, それとも 12 が結合された物でしょうか. どちらの場合においても間違ってはおらず, これが JSON::XS がこれらのケースを許容しないで保守的な立場を取る理由です. For example, is the string 1 a single JSON number, or is it simply the start of 12? Or is 12 a single JSON number, or the concatenation of 1 and 2? In neither case you can tell, and this is why JSON::XS takes the conservative route and disallows this case.

EXAMPLES

いくつかの例を挙げることでより分かりやすくなるでしょう. 先ず, decode_prefix と同じように動作する簡単な例から始めてみましょう: 文字列の最初から JSON オブジェクトをデコードして, JSON オブジェクトの後にある部分を区別してみたいとしましょう: Some examples will make all this clearer. First, a simple example that works similarly to decode_prefix: We want to decode the JSON object at the start of a string and identify the portion after the JSON object:

   my $text = "[1,2,3] hello";

   my $json = new JSON::XS;

   my $obj = $json->incr_parse ($text)
      or die "expected JSON object or array at beginning of string";

   my $tail = $json->incr_text;
   # $tail now contains " hello"

簡単ですね. Easy, isn't it?

ではもうちょっと複雑な例を見てみましょう: TCP ストリームからいくつかのリクエストを読み込むような 仮想的なプロトコルを想像してみましょ, そして各リクエストは JSON 配列で, それらの間には区切りを持ちません (実際には改行文字が"区切り"としてよく使われていて, それは JSON テキストの始まりでは白空白として処理されます, これがあると telnet でプロトコルをしゃべってみることができます...) Now for a more complicated example: Imagine a hypothetical protocol where you read some requests from a TCP stream, and each request is a JSON array, without any separation between them (in fact, it is often useful to use newlines as "separators", as these get interpreted as whitespace at the start of the JSON text, which makes it possible to test said protocol with telnet...).

次にあるのが実際に行う処理です (これをイベントベースで記述するのも 簡単でしょう): Here is how you'd do it (it is trivial to write this in an event-based manner):

   my $json = new JSON::XS;

   # read some data from the socket
   # ソケットからデータをいくらか読み込み.
   while (sysread $socket, my $buf, 4096) {

      # split and decode as many requests as possible
      # 複数のリクエストを可能な分だけ分割してデコード.
      for my $request ($json->incr_parse ($buf)) {
         # act on the $request
         # $request で何か動作.
      }
   }

もうちょっと複雑な例もやってみましょう: JSON オブジェクト若しくは配列がコンマ文字で(省略可能に) 区切られている文字列を持っているとしましょう(例えば [1],[2], [3]). これらをパーすするには JSON テキストの間にあるコンマを読み飛ばす 必要があり, ここで incr_text のlvalue 特性が役に立ちます: Another complicated example: Assume you have a string with JSON objects or arrays, all separated by (optional) comma characters (e.g. [1],[2], [3]). To parse them, we have to skip the commas between the JSON texts, and here is where the lvalue-ness of incr_text comes in useful:

   my $text = "[1],[2], [3]";
   my $json = new JSON::XS;

   # void context, so no parsing done
   # void コンテキスト, つまりパースは行わない.
   $json->incr_parse ($text);

   # now extract as many objects as possible. note the
   # use of scalar context so incr_text can be called.
   # そして可能な分だけ複数のオブジェクトを取り出し.
   # incr_text が呼び出せるようにスカラーコンテキストを使用.
   while (my $obj = $json->incr_parse) {
      # do something with $obj
      # $obj で何かする.

      # now skip the optional comma
      # そして省略可能なコンマを読み飛ばす.
      $json->incr_text =~ s/^ \s* , //x;
   }

ではもっと複雑な例にいってみましょう: とっても大きな JSON のオブジェクトの配列があるとしましょう, これは数ギガバイトありますが, それを読み込みたいとします, とは行ってもそれを一度にメモリ上に読み込むことは出来ません (これは実際に起こることです:). Now lets go for a very complex example: Assume that you have a gigantic JSON array-of-objects, many gigabytes in size, and you want to parse it, but you cannot load it into memory fully (this has actually happened in the real world :).

えぇ, あなたの負けです, 自分で JSON パーサを実装しなければなりません. けれども JSON::XS はまだその手助けをすることが出来ます: あなたが(とても単純な)配列パーサを実装して, JSON::XS に配列の要素をデコードさせることで, これはその完全な JSON オブジェクトを手に入れることになります (でもこれは例えば配列の要素が JSON 数値だった場合にはうまくいかない でしょう): Well, you lost, you have to implement your own JSON parser. But JSON::XS can still help you: You implement a (very simple) array parser and let JSON::XS decode the array elements, which are all full JSON objects on their own (this wouldn't work if the array elements could be JSON numbers, for example):

   my $json = new JSON::XS;

   # open the monster
   # 怪物を開く.
   open my $fh, "<bigfile.json"
      or die "bigfile: $!";

   # first parse the initial "["
   # 開始の "[" をパース.
   for (;;) {
      sysread $fh, my $buf, 65536
         or die "read error: $!";
      $json->incr_parse ($buf); # void context, so no parsing
                                # void context, つまりパースはまだしない.

      # Exit the loop once we found and removed(!) the initial "[".
      # In essence, we are (ab-)using the $json object as a simple scalar
      # we append data to.
      # 開始の "[" が見つかってそれを取り除い(!)たらすぐにループを抜ける.
      # 実際のところ単なるデータ積み置き用のスカラーの代わりに
      # $json オブジェクトを利用(濫用)しています.
      last if $json->incr_text =~ s/^ \s* \[ //x;
   }

   # now we have the skipped the initial "[", so continue
   # parsing all the elements.
   # で, 開始の "[" は読み終わったので,
   # 全ての要素の読み込みに移ります.
   for (;;) {
      # in this loop we read data until we got a single JSON object
      # このループの中で JSON オブジェクトを1つ得るまで
      # データを読み込み.
      for (;;) {
         if (my $obj = $json->incr_parse) {
            # do something with $obj
            # $obj に何かする.
            last;
         }

         # add more data
         # データを追加.
         sysread $fh, my $buf, 65536
            or die "read error: $!";
         $json->incr_parse ($buf); # void context, so no parsing
                                   # void context, つまりパースはまだしない.
      }

      # in this loop we read data until we either found and parsed the
      # separating "," between elements, or the final "]"
      # こちらのループでは要素区切りの "," か終端の "]" を
      # 見つけて取り除くまでデータを読み込み.
      for (;;) {
         # first skip whitespace
         # まず白空白の除去.
         $json->incr_text =~ s/^\s*//;

         # if we find "]", we are done
         # "]" が見つかればこれで完了.
         if ($json->incr_text =~ s/^\]//) {
            print "finished.\n";
            exit;
         }

         # if we find ",", we can continue with the next element
         # "," が見つかれば次の要素に進む.
         if ($json->incr_text =~ s/^,//) {
            last;
         }

         # if we find anything else, we have a parse error!
         # (訳注:内容があるのに)何も見つけれなければ, これはパースエラー!
         if (length $json->incr_text) {
            die "parse error near ", $json->incr_text;
         }

         # else add more data
         # それ以外の時はデータを追加.
         sysread $fh, my $buf, 65536
            or die "read error: $!";
         $json->incr_parse ($buf); # void context, so no parsing
                                   # void context, つまりパースはまだしない.
      }

これは複雑な例ですが, 複雑さの大半は 正しくあろうとしていることから来ています (もし間違っていたら辛抱してください, この例は実行していないのです:) This is a complex example, but most of the complexity comes from the fact that we are trying to be correct (bear with me if I am wrong, I never ran the above example :).


マッピング MAPPING

このセクションでは JSON::XS が Perl の値をどのように JSON の値へと マッピングしているかそしてその逆を行っているかについて説明します. これらのマッピングはほとんどの状況でラウンドトリップ性を保ちながら 自動的に"正しいことを行う"ように設計されています(入力したものは 等価な何かとして出力されます). This section describes how JSON::XS maps Perl values to JSON values and vice versa. These mappings are designed to "do the right thing" in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent).

もっと進むために: 以下の説明に注意してください, 小文字の perl は Perl インタプリタを示し, 大文字の Perl は抽象化した Perl 言語 そのものを参照します. For the more enlightened: note that in the following descriptions, lowercase perl refers to the Perl interpreter, while uppercase Perl refers to the abstract Perl language itself.

JSON -> PERL

object

JSON オブジェクトは Perl のハッシュリファレンスになります. オブジェクトキーの順序は保存されません(JSONもそれ自身ではオブジェクト キーの順序を保存しません). A JSON object becomes a reference to a hash in Perl. No ordering of object keys is preserved (JSON does not preserve object key ordering itself).

array

JSON の配列は Perl では配列リファレンスになります. A JSON array becomes a reference to an array in Perl.

string

JSON の文字列は Perl では文字列スカラーになります - JSON のユニコード コードポイントは Perl 文字列で同じコードポイントとして表現されます, なので手作業でのデコードは不要です. A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary.

number

JSON での数値はその範囲と小数部に応じて perl での整数, 数値( 浮動小数点)若しくは文字列スカラーになります. Perl レベルでは, これらの違いはなく, 全ての詳細な変換は Perl によって処理されますが, 整数の方が若干メモリ 消費が少なく浮動小数点数よりも実質より多くを表現できることが あります. A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers.

数値が数字のみからなっているときには, JSON::XS はそれを整数値として表現しようとします. もしこれができなければ精度を失うことがなければ 数値(浮動小数点数)として表現します. それ以外であれば文字列値として残します (この時 JSON 数値は JSON 文字列へと再エンコードされるため ラウンドトリップ能力が失われます). If the number consists of digits only, JSON::XS will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded to a JSON string).

分数若しくは指数部を含んだ数値は精度を失うことなしに数値 (浮動小数点数)として表現されます (この時完全なラウンドトリップ能力は失わることがありますが, JSON 数値はまだ JSON 数値へと再エンコードされます). Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number).

true, false

これらの JSON アトムはそれぞれ JSON::XS::true 及び JSON::XS::false になります. これらはだいたい正確に 数値 1 及び 0 のように動作するようにオーバーロード されています. スカラーが JSON 真偽値なのかどうかは JSON::XS::is_bool 関数を使って判断できます. These JSON atoms become JSON::XS::true and JSON::XS::false, respectively. They are overloaded to act almost exactly like the numbers 1 and 0. You can check whether a scalar is a JSON boolean by using the JSON::XS::is_bool function.

null

JSON の null アトムは Perl では undef になります. A JSON null atom becomes undef in Perl.

PERL -> JSON

Perl から JSON へのマッピングは若干複雑です, Perl は本当に型の無い言語で あり, そのため Perl の値を意味するJSON の型は推測するしかありません. The mapping from Perl to JSON is slightly more difficult, as Perl is a truly typeless language, so we can only guess which JSON type is meant by a Perl value.

ハッシュリファレンス hash references

Perl のハッシュリファレンスは JSON のオブジェクトになります. ハッシュのキー(若しくは JSON オブジェクト)には固有の順序はないため 同じプログラムでも実行するたびに変化するけれどプログラムの1回の 同じ実行内であれば大抵同じになる疑似ランダム順でエンコードされます. JSON::XS はオプションでハッシュキーをソートすることが出来ます( canonicalフラグで決定されます), このため同じデータ構造で( そして同じ設定とJSON::XSのバージョンで)あれば同じ JSON テキストへと シリアライズされます, しかしこれは実行時のオーバーヘッドとなる上に 役立つのはまれなことです, 例えば幾つかの JSON テキストで 他のテキストと等価か比較したいとき. Perl hash references become JSON objects. As there is no inherent ordering in hash keys (or JSON objects), they will usually be encoded in a pseudo-random order that can change between runs of the same program but stays generally the same within a single run of a program. JSON::XS can optionally sort the hash keys (determined by the canonical flag), so the same datastructure will serialise to the same JSON text (given same settings and version of JSON::XS), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some JSON text against another for equality.

配列リファレンス array references

Perl の配列リファレンスは JSON の配列となります. Perl array references become JSON arrays.

その他のリファレンス other references

その他のブレスされていないリファレンスは大抵は受け付けられずに 例外が投げられますが, 整数 0 及び 1 のリファレンスだけは JSON のアトム false 及び true へと変換されます. ぱっとみを 分かり易くするために JSON::XS::false 及び JSON::XS::true を 使うことも出来ます. Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers 0 and 1, which get turned into false and true atoms in JSON. You can also use JSON::XS::false and JSON::XS::true to improve readability.

   encode_json [\0, JSON::XS::true]      # yields [false,true]
JSON::XS::true, JSON::XS::false

これらの特殊な値はそれぞれ JSON true 及び JSON false の値になります. やりたければ \1 及び \0 を直接使うこともできます. These special values become JSON true and JSON false values, respectively. You can also use \1 and \0 directly if you want.

ブレスされたオブジェクト blessed objects

ブレスされたオブジェクトは JSON では直接は受け付けられません. それを行うためのいくつかのオプションとして allow_blessed 及び convert_blessed メソッドを参照してください: 基本的に, 例外を投げるか, ブレスされていないかのようにそのリファレンスを エンコーディングするか, 若しくは独自のシリアライザメソッドを提供するか の選択になります. Blessed objects are not directly representable in JSON. See the allow_blessed and convert_blessed methods on various options on how to deal with this: basically, you can choose between throwing an exception, encoding the reference as if it weren't blessed, or provide your own serialiser method.

シンプルなスカラー simple scalars

単純な Perl スカラー(リファレンスではない全てのスカラー)は エンコードがとても難しいオブジェクトです: JSON::XS は 未定義のスカラーは JSON の null 値に, エンコーディグングまでに スカラコンテキストで使われたスカラーは JSON 文字列に, そして それ以外の全ては数値としてエンコードします: Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: JSON::XS will encode undefined scalars as JSON null values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value:

   # dump as number
   # 数値としてダンプ.
   encode_json [2]                      # yields [2]
   encode_json [-3.0e17]                # yields [-3e+17]
   my $value = 5; encode_json [$value]  # yields [5]

   # used as string, so dump as string
   # 文字列として使ったので文字列としてダンプ.
   print $value;
   encode_json [$value]                 # yields ["5"]

   # undef becomes null
   # undef は null に.
   encode_json [undef]                  # yields [null]

文字列化を行うことで強制的にJSON文字列にすることが出来ます: You can force the type to be a JSON string by stringifying it:

   my $x = 3.1; # some variable containing a number
   "$x";        # stringified
   $x .= "";    # another, more awkward way to stringify
   print $x;    # perl does it for you, too, quite often
   
   my $x = 3.1; # 数値を含んでいる変数
   "$x";        # 文字列化
   $x .= "";    # 文字列化する awk っぽい方法
   print $x;    # かわりに perl がやってくれる

数値化を行うことで強制的にJSON 数値型にすることが出来ます: You can force the type to be a JSON number by numifying it:

   my $x = "3"; # some variable containing a string
   $x += 0;     # numify it, ensuring it will be dumped as a number
   $x *= 1;     # same thing, the choice is yours.
   
   my $x = "3"; # 文字列を含んでいる変数
   $x += 0;     # 数値化, これによって数値としてダンプされることを保証
   $x *= 1;     # 同様, 好きな方を選んでください

いまのところ他の型への強制を 読みづらくなることなしにおこなうことはできません. もし その方法が必要であれば私に問い合わせてください (なぜそれが必要なのかの説明を忘れないでくださいね :). You can not currently force the type in other, less obscure, ways. Tell me if you need this capability (but don't forget to explain why it's needed :).


エンコーディング/文字集合フラグの説明 ENCODING/CODESET FLAG NOTES

関心のある読者はエンコーディングか文字集合(codeset)を示す いくつかのフラグ - utf8, latin1 そして ascii を 目にしているでしょう. これらはそれらが何をするのか 戸惑うかもしれません, なのでここで簡単に比較してみます. The interested reader might have seen a number of flags that signify encodings or codesets - utf8, latin1 and ascii. There seems to be some confusion on what these do, so here is a short comparison:

utf8encode で作られた(そして decode が期待する) JSON テキストが UTF-8 エンコードされているかどうかを, そして latin1 及び asciiencode がそのコード範囲の 外側になる文字をエスケープするかどうかのみを制御します. これらのフラグはどちらもそれぞれにぶつかり(conflict)ますが, けれどもいくつかの組み合わせはわかりにくいでしょう. utf8 controls whether the JSON text created by encode (and expected by decode) is UTF-8 encoded or not, while latin1 and ascii only control whether encode escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others.

全てのフラグは encode 及び decode に対照的に関係する点に 気をつけてください, つまり, いずれかの組み合わせでエンコードされた テキストは, 同じ組み合わせが使われたときに正しくデコードできます - 多くの場合は, もしエンコードとデコードで異なるフラグ設定を 使った場合にはどこかでバグとなるでしょう. Care has been taken to make all flags symmetrical with respect to encode and decode, that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used - in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere.

詳しい説明は以下に続きます. "コードセット" は単純に文字とコードポイントの組の抽象的な集合で, エンコーディングがこれらのコードポイント値を取って, 私たちの場合ではオクテットへとエンコードされます. Unicode が(それ以外もそうですが)コードセットであり, UTF-8 がエンコーディングです, そして ISO-8859-1 (= latin 1) 及び ASCII はコードセットであり そして同時にエンコーディングでもあります, これは混乱しますが. Below comes a verbose discussion of these flags. Note that a "codeset" is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and encodes them, in our case into octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets and encodings at the same time, which can be confusing.

utf8 フラグが無効になっているとき utf8 flag disabled

utf8 が無効になっているとき(デフォルト)は, encode/decode は Unicode 文字列を生成/予期します, つまり, 高位の Unicode 文字 (> 255)はそのような文字へと エンコードされ, 同じようなそのような文字はそのようにデコードされます, それらはそれぞれ Unicode コードポイント若しくは Unicode 文字としての "(再)解釈"を除いて変更はされません (Perl においては, これらは おかしな/奇妙な/馬鹿なことをしているのでなければ文字列中で同じ物です). When utf8 is disabled (the default), then encode/decode generate and expect Unicode strings, that is, characters with high ordinal Unicode values (> 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except "(re-)interpreting" them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff).

これは自分でエンコードしたいとき (例えば UTF-16 でエンコードされた JSON テキストが欲しい)や他のレイヤがエンコードしてくれる (例えば始めは本当に UTF-8 では欲しくはなくて ファイルハンドルから 端末に出力するときに透過的に Perl が別の時にエンコードしてくれるとき) に便利です. This is useful when you want to do the encoding yourself (e.g. when you want to have UTF-16 encoded JSON texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to UTF-8 you certainly do NOT want to UTF-8 encode your data first and have Perl encode it another time).

utf8 フラグが有効になっているとき utf8 flag enabled

utf8-フラグが有効になっていると, encod/decode は 全ての文字を対応する UTF-8 多バイト列を使って 全ての文字をエンコードし, 入力が UTF-8 でエンコードされている ことを期待するようになります, つまり, 入力文字列の "文字" には UTF-8 が許さない 255 より大きな値は存在しません. If the utf8-flag is enabled, encode/decode will encode all characters using the corresponding UTF-8 multi-byte sequence, and will expect your input strings to be encoded as UTF-8, that is, no "character" of the input string must have any value > 255, as UTF-8 does not allow that.

utf8 フラグは従って2つのモードのスイッチとなります: 無効になっていると Perl では Unicode 文字列として扱われ, 有効になっていると Perl では UTF-8 エンコードされたオクテット/バイナリ 文字列として扱われます. The utf8 flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get an UTF-8 encoded octet/binary string in Perl.

latin1 若しくは ascii フラグが有効になっているとき latin1 or ascii flags enabled

latin1 (若しくは ascii) が有効になっていると, encode は順序値が 255 より大きい(ascii では 127 より大きい)文字 をエスケープして, 残りの文字を utf8 フラグで指定された文字に エンコードします. With latin1 (or ascii) enabled, encode will escape characters with ordinal values > 255 (> 127 with ascii) and encode the remaining characters as specified by the utf8 flag.

utf8 が無効になっていると, その結果はその文字集合は 正しくエンコードもされます (両方とも Unicode の正当なサブセットで, Unicode 文字列の 256 未満の全ての文字は ISO-8859-1 文字列と同じであり, Unicode 文字列の 128 未満の全ての文字は Perl における ASCII 文字列と同じです). If utf8 is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values < 256 is the same thing as a ISO-8859-1 string, and a Unicode string with all character values < 128 is the same thing as an ASCII string in Perl).

utf8 が有効になっていると, この時も正しく UTF-8 エンコードされた 文字列を得ることができます, これらのフラグにかかわらず, いくつかの文字は \uXXXX でエスケープされます. If utf8 is enabled, you still get a correct UTF-8-encoded string, regardless of these flags, just some more characters will be escaped using \uXXXX then before.

ISO-8859-1 でエンコードされた文字列は UTF-8 エンコーディングとは互換性がないことに注意してください, ASCII エンコードされた文字列では互換性があるにもかかわらずです. これは ISO-8859-1 エンコーディングは UTF-8 のサブセットではないためです, (ISO-8859-1 コードセット は Unicode のサブセットであるにもかかわらず), そして ASCII は UTF-8 のサブセットであるにもかかわらず. Note that ISO-8859-1-encoded strings are not compatible with UTF-8 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 codeset being a subset of Unicode), while ASCII is.

意外なことに, deocode はこれらのフラグを無視します, そして全ての入力は utf8 フラグに支配されます. それが無効であれば, ISO-8859-1 及び ASCII エンコードされた 文字列としてデコードされます, これはどちらも Unicode の厳密なサブセットで あるためです. それが有効になっていれば, UTF-8 エンコードされた文字列を 正しくデコードできます. Surprisingly, decode will ignore these flags and so treat all input values as governed by the utf8 flag. If it is disabled, this allows you to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.

つまり latin1 及び asciiutf8 フラグとは互換がありません - これらは JSON の出力エンジンが文字をエスケープするかどうかにだけ 作用します. So neither latin1 nor ascii are incompatible with the utf8 flag - they only govern when the JSON output engine escapes a character or not.

latin1 の主な用法としてはバイナリデータを比較的効率的に JSON として格納できる点でしょうか, 多くの JSON デコーダとの 相互運用性を壊しますが. The main use for latin1 is to relatively efficiently store binary data as JSON, at the expense of breaking compatibility with most JSON decoders.

ascii の主な用法としては出力が 127 を超える値を含まないように 強制させる点です, これは出力された文字を UTF-8, ISO-8859-1, ASCII, KOI8-R や他の文字集合及び8ビットエンコーディングとして 処理できることを意味します, そしてそれでもなお同じデータ構造を 復元できます. これは JSON 転送チャンネルが 8-bit クリーンで なかったり, 壊され(mangled)たり(例えばメール等)する時でも, ASCII は世界で使われているほとんどの 8-bit 及び多バイトエンコーディング の適切なサブセットであるため動作します. The main use for ascii is to force the output to not contain characters with values > 127, which means you can interpret the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and 8-bit-encoding, and still get the same data structure back. This is useful when your channel for JSON transfer is not 8-bit clean or the encoding might be mangled in between (e.g. in mail), and works because ASCII is a proper subset of most 8-bit and multibyte encodings in use in the world.

JSON と YAML JSON and YAML

JSON は YAML のサブセット(若しくはほぼサブセット)であると 時々耳にするでしょう. これは, しかしながら, とても ヒステリックなことであり, 真実からはほど遠いことです. 一般的には, JSON::XS が正しい YAML をはき出すように設定する 方法はありません. You often hear that JSON is a subset (or a close subset) of YAML. This is, however, a mass hysteria and very far from the truth. In general, there is no way to configure JSON::XS to output a data structure as valid YAML.

もしどうしても JSON::XS を使って YAML を生成しなければ ならないのであれば(今後のバージョンで変更されるかもしれない) 以下のアルゴリズムを使ってみるとよいでしょう: If you really must use JSON::XS to generate YAML, you should use this algorithm (subject to change in future versions):

   my $to_yaml = JSON::XS->new->utf8->space_after (1);
   my $yaml = $to_yaml->encode ($ref) . "\n";

これは大抵正しい YAML としてパース可能な JSON テキストを 生成するでしょう. しかし YAML は JSON の持っていない (簡単な)オブジェクトキーの長さに対するハードコードされた 制限を持っているので, ハッシュキーが YAML で許可されている 1024 文字より短くなるように気をつけてください. This will usually generate JSON texts that also parse as valid YAML. Please note that YAML has hardcoded limits on (simple) object key lengths that JSON doesn't have, so you should make sure that your hash keys are noticeably shorter than the 1024 characters YAML allows.

それ以外にもまだ知らない非互換もあるかもしれません. 一般的に JSON の生成ロジックを使って YAML を 生成及びその逆, 若しくは YAML パーサを使って JSON のパースを及びその逆を行うべきではありません: 厳密な相互運用に関する問題を引き起こす可能性が高いでしょう. There might be other incompatibilities that I am not aware of. In general you should not try to generate YAML with a JSON generator or vice versa, or try to parse JSON with a YAML parser or vice versa: chances are high that you will run into severe interoperability problems.

(*)

私は Brian Ingerson (YAML 仕様の著者の一人)から何回も このパラグラフを削除するように圧力を受けました, 彼が実際に非互換が存在することを認めているにもかかわらずです. 私はこの"JSON は YAML"の嘘で個人的にかみつかれて, 混乱してこれらの記事を人々に伝えておくと言いました, なので同じ問題に何回も陥らないでください. この後, Brian は私のことを(引用)全く役に立たない間抜け(引用ここまで) と呼びました. I have been pressured multiple times by Brian Ingerson (one of the authors of the YAML specification) to remove this paragraph, despite him acknowledging that the actual incompatibilities exist. As I was personally bitten by this "JSON is YAML" lie, I refused and said I will continue to educate people about these issues, so others do not run into the same problem again and again. After this, Brian called me a (quote)complete and worthless idiot(unquote).

私の意見としては, YAMLやいくつかのその提案に関する間違った 説明に関して本当に明白に話題をだした人々に圧力を掛けたり 侮蔑したりするのではなく, 私は JSON の仕様(これは難しくも 長くもありません)を読んでみることを優しく提案します, 実際の互換性に関する嘘を何年にもわたって広めたり それが真実ではないと指摘した人を黙らせようとしたりするのではなく. In my opinion, instead of pressuring and insulting people who actually clarify issues with YAML and the wrong statements of some of its proponents, I would kindly suggest reading the JSON spec (which is not that difficult or long) and finally make YAML compatible to it, and educating users about the changes, instead of spreading lies about the real compatibility for many years and trying to silence people who point out that it isn't true.

速度 SPEED

以下の表にあるように, JSON::XS は驚くくらい高速です. このデータは JSON::XS 配布物の中の eg/bench プログラムで生成されました, あなたの 環境でも簡単に比較してみることができます. It seems that JSON::XS is surprisingly fast, as shown in the following tables. They have been generated with the help of the eg/bench program in the JSON::XS distribution, to make it easy to compare on your own system.

はじめにとても短い一行の JSON 文字列を使って様々なモジュールで比較 したものです: First comes a comparison between various modules using a very short single-line JSON string:

   {"method": "handleMessage", "params": ["user1", "we were just talking"], \
   "id": null, "array":[1,11,234,-5,1e5,1e7, true,  false]}

これは1秒間あたりの ecode/decode 数を示します (JSON:XS は 関数インターフェース, JSON::XS/2 は OO インターフェースで pretty-printing とハッシュキーソートを有効にしたもの, JSON::XS/3 は shrink を有効にしたものを使っています). 大きい方が優秀です. It shows the number of encodes/decodes per second (JSON::XS uses the functional interface, while JSON::XS/2 uses the OO interface with pretty-printing and hashkey sorting enabled, JSON::XS/3 enables shrink). Higher is better:

   module     |     encode |     decode |
   -----------|------------|------------|
   JSON 1.x   |   4990.842 |   4088.813 |
   JSON::DWIW |  51653.990 |  71575.154 |
   JSON::PC   |  65948.176 |  74631.744 |
   JSON::PP   |   8931.652 |   3817.168 |
   JSON::Syck |  24877.248 |  27776.848 |
   JSON::XS   | 388361.481 | 227951.304 |
   JSON::XS/2 | 227951.304 | 218453.333 |
   JSON::XS/3 | 338250.323 | 218453.333 |
   Storable   |  16500.016 | 135300.129 |
   -----------+------------+------------+

これによると, JSON::XS は pretty-printing とキーのソートを 有効にしていても JSON::DWIW よりエンコードおよそ5倍, デコードで およそ3倍, そして JSON よりおよそ40倍高速です. 小さなデータに有利な Storable でも比較しています. That is, JSON::XS is about five times faster than JSON::DWIW on encoding, about three times faster on decoding, and over forty times faster than JSON, even with pretty-printing and key sorting. It also compares favourably to Storable for small amounts of data.

もっと長いテスト文字列(おおよそ 18KB, Yahoo! Locals 検索 API (http://dist.schmorp.de/misc/json/long.json で生成)で試してみた結果: Using a longer test string (roughly 18KB, generated from Yahoo! Locals search API (http://dist.schmorp.de/misc/json/long.json).

   module     |     encode |     decode |
   -----------|------------|------------|
   JSON 1.x   |     55.260 |     34.971 |
   JSON::DWIW |    825.228 |   1082.513 |
   JSON::PC   |   3571.444 |   2394.829 |
   JSON::PP   |    210.987 |     32.574 |
   JSON::Syck |    552.551 |    787.544 |
   JSON::XS   |   5780.463 |   4854.519 |
   JSON::XS/2 |   3869.998 |   4798.975 |
   JSON::XS/3 |   5862.880 |   4798.975 |
   Storable   |   4445.002 |   5235.027 |
   -----------+------------+------------+

ここでも, JSON::XS は大きく抜き出ています(驚くほどではないけれど デコードが高速な Storable を除いて). Again, JSON::XS leads by far (except for Storable which non-surprisingly decodes faster).

大きなUnicode文字を対象に含んでいる大きな文字列では, 幾つかの モジュール(例えば JSON::PC) の方が JSON::XS より速いことも ありますが, それが返す結果はUnicode処理が無い(若しくは間違っている) 為に壊れています. それ以外では適切なデコード及びエンコードは拒否されて しまいます, そのためこのケースにおける対等な比較を準備するのは不可能 です. On large strings containing lots of high Unicode characters, some modules (such as JSON::PC) seem to decode faster than JSON::XS, but the result will be broken due to missing (or wrong) Unicode handling. Others refuse to decode or encode properly, so it was impossible to prepare a fair comparison table for that case.


セキュリティ的な考慮点 SECURITY CONSIDERATIONS

プロトコル内で JSON を使っているのであれば 信頼されていない潜在的に敵意のある生成物について いつかの方法について話しておく必要があります. When you are using JSON in a protocol, talking to untrusted potentially hostile creatures requires relatively few measures.

はじめに, 使用する JSON デコーダはセキュアであるべきです, つまり, どんなバッファオーバフローも無いべきです. 明らかに, このモジュールはそれを保証するべきでありそうあるようにとても がんばっていますが, あなたはそれを知らないでしょう. First of all, your JSON decoder should be secure, that is, should not have any buffer overflows. Obviously, this module should ensure that and I am trying hard on making that true, but you never know.

2番目に, リソース枯渇攻撃を無効化する必要があります. これは 受け付ける JSON テキストのサイズを制限するか確認するべきと いうことです, これによってリソースが枯渇したときに よい方向に働くでしょう(例えば安全にクラッシュできるように プロセスを分割したり). JSON テキストのオクテット若しくは 文字単位でのサイズは Perl 構造をデコードするために必要な リソースのサイズのよい指標になります. JSON::XS は JSON テキストのサイズを調べることができますが, それが既にメモリ内にあるのでは遅すぎます, なので文字列を受け付ける前にサイズを調べる必要があるでしょう. Second, you need to avoid resource-starving attacks. That means you should limit the size of JSON texts you accept, or make sure then when your resources run out, that's just fine (e.g. by using a separate process that can crash safely). The size of a JSON text in octets or characters is usually a good indication of the size of the resources required to decode it into a Perl structure. While JSON::XS can check the size of the JSON text, it might be too late when you already have it in memory, so you might want to check the size before you accept the string.

3番目に, JSON::XS はオブジェクトや配列をデコードする時に, C スタックを使って再帰します. C スタックは限界のあるリソースです: 例えば 8MB のスタックサイズをもつ私の amd64 マシンでは 180k 個の ネストした配列をデコードできますが, ネストした JSON オブジェクトでは 14k 個だけでした(croak時に一時領域を解放するために perl 自身が深く 再帰するためです). この制限を超えたとき, プログラムはクラッシュ します. ここでは慎重に, デフォルトのネスト制限は 512 に設定されて います. もしあなたの処理でもっとちいさなスタックしかないのであれば, max_depth メソッドを使って適切な設定に調整するべきです. Third, JSON::XS recurses using the C stack when decoding objects and arrays. The C stack is a limited resource: for instance, on my amd64 machine with 8MB of stack size I can decode around 180k nested arrays but only 14k nested JSON objects (due to perl itself recursing deeply on croak to free the temporary). If that is exceeded, the program crashes. To be conservative, the default nesting limit is set to 512. If your process has a smaller stack, you should adjust this setting accordingly with the max_depth method.

他にも何か私の考えの及ばないところで暴発することがあるかもしれません. そうなってしまったときには残ったかけらを持っておいてください. 助言できるようにいつも門戸をひらいていますので... Something else could bomb you, too, that I forgot to think of. In that case, you get to keep the pieces. I am always open for hints, though...

また JSON::XS はエラーメッセージの中に Perl データ構造の中身を 漏らしてしまうことがある点を忘れないでください, つまり公開したくはない情報をシリアライズするときには JSON::XS の投げる例外を信頼できる人以外の前にでないように するべきでしょう. Also keep in mind that JSON::XS might leak contents of your Perl data structures in its error messages, so when you serialise sensitive information you might want to make sure that exceptions thrown by JSON::XS will not end up in front of untrusted eyes.

そして最後にとはいえ大きなことではないのですが, 私も考えていなかった他の何かがあなたを爆破することが あるかもしれません. そのようなことがあったときには, その欠片を集めておいてください. 私はいつでもヒントを 歓迎していますので. And last but least, something else could bomb you that I forgot to think of. In that case, you get to keep the pieces. I am always open for hints, though...

もしブラウザの JavaScript で利用するためのパケットとして返すために JSON::XS を使っているのなら 幾つかの攻撃ベクタに対して脆弱でないかを確認するために http://jpsykes.com/47/practical-csrf-and-json-security を見ておくべきです(これらは本当にブラウザ設計のバグですが, メジャーなブラウザの開発者たちは安全性ではなく機能のみに 注意しているのであなたがバグに対しては注意を払っておく 必要があります). If you are using JSON::XS to return packets to consumption by JavaScript scripts in a browser you should have a look at http://jpsykes.com/47/practical-csrf-and-json-security to see whether you are vulnerable to some common attack vectors (which really are browser design bugs, but it is still you who will have to deal with it, as major browser developers care only for features, not about getting security right).


スレッド THREADS

このモジュールはスレッドセーフに関しては考慮しておらず また Perl がスレッドサポートを得るまでこれを変更する予定もありません (恐ろしく低速な"threads"と呼ばれる単に遅くて肥大化した プロセスのシミュレーションではなく, とても高速で, 安価で, より良い, fork を使いましょう). This module is not guaranteed to be thread safe and there are no plans to change this until Perl gets thread support (as opposed to the horribly slow so-called "threads" which are simply slow and bloated process simulations - use fork, it's much faster, cheaper, better).

(実際のところ動作はするでしょう, でも警告はしましたよ). (It might actually work, but you have been warned).


バグ BUGS

このモジュールの目標として正しくあることがありますが, 不幸なことにこれはバグがないということを意味しているわけではあなく, 設計にバグがないことと考えています. このモジュールはまだとても若く テストも十分なわけではありません. バグ報告がきたらすぐに修正するでしょう. While the goal of this module is to be correct, that unfortunately does not mean it's bug-free, only that I think its design is bug-free. It is still relatively early in its development. If you keep reporting bugs they will be fixed swiftly, though.

rt.cpan.org や他のバグ報告サービスの利用は控えてください. 故あって連絡用のアドレスはモジュールに記載しています. Please refrain from using rt.cpan.org or any other bug reporting service. I put the contact address into my modules for a reason.


関連項目 SEE ALSO

The json_xs command line utility for quick experiments.


著者 AUTHOR

 Marc Lehmann <schmorp@schmorp.de>
 http://home.schmorp.de/

和訳 TRANSALTE TO JAPANESE

 山科 氷魚 (YAMASHINA Hio) <hio@hio.jp>

原典: JSON-XS VERSION 2.23-2.231. 翻訳日: 2008-10-25. (JSON-XS-0.2, 2007-03-23) Original distribution is JSON-XS VERSION 2.23-2.231. Translated on 2008-10-25. (JSON-XS-0.2, 2007-03-23)

JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ
JSON::XS - JSON serialising/deserialising, done correctly and fast

索引 INDEX

JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ
JSON::XS - JSON serialising/deserialising, done correctly and fast