英語版
このページの英語版を見る

std.json

JavaScript Object Notation の値を読み書きする機能を実装する。
JavaScript Object Notationは、ウェブサービスや設定ファイルでよく使われる軽量なデータ交換フォーマットだ。 人間が読み書きするのも簡単だし、機械が解析して生成するのも簡単だ。
警告JSONValue 、小規模な使用には問題ないが、数百メガバイトの規模になると、以下のような問題が発生することが知られている。 GCの問題を引き起こし、悪化させることが知られている。問題が発生した場合は、ストリーム・パーサーに置き換えてみてほしい。以下を参照のこと。 https://forum.dlang.org/post/dzfyaxypmkdrpakmycjv@forum.dlang.org も参照のこと。
Authors:
Jeremie Pelletier, David Herberth

出典 std/json.d

Examples:
import std.conv : to;

// ファイルまたはjsonの文字列を使用可能な構造に解析する
string s = `{ "language": "D", "rating": 3.5, "code": "42" }`;
JSONValue j = parseJSON(s);
// jとj["language"]はJSONValueを返す、
// j["language"].strは文字列を返す
writeln(j["language"].str); // "D"
writeln(j["rating"].floating); // 3.5

// 型をチェックする
long x;
if (const(JSONValue)* code = "code" in j)
{
    if (code.type() == JSONType.integer)
        x = code.integer;
    else
        x = to!int(code.str);
}

// json構造体を作成する
JSONValue jj = [ "language": "D" ];
// ratingがまだ存在しないので、.objectを使用して次のように代入する
jj.object["rating"] = JSONValue(3.5);
// リストに割り当てる配列を作成する
jj.object["list"] = JSONValue( ["a", "b", "c"] );
// listはすでに存在しているので、.objectはオプションである
jj["list"].array ~= JSONValue("D");

string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`;
writeln(jj.toString); // jjStr
enum JSONFloatLiteral: string;
JSON文字列内で特殊な浮動小数点値を表現するために使用される文字列リテラル。
nan
浮動小数点NaNの文字列表現
inf
浮動小数点数Infinityの文字列表現
negativeInf
浮動小数点負のInfinityの文字列表現
enum JSONOptions: int;
JSONのエンコードおよび解析方法を制御するフラグ。
none
標準的な構文解析とエンコード
specialFloatLiterals
NaNとInf float値を文字列としてエンコードする。
escapeNonAsciiChars
非 ASCII 文字を Unicode エスケープシーケンスでエンコードする。
doNotEscapeSlashes
スラッシュ('/')をエスケープしない。
strictParsing
解析時にはRFC-8259の文法に厳密に従う。
enum JSONType: byte;
JSON型の列挙
null_

string

integer

uinteger

float_

array

object

true_

false_
JSONValue の"型"を示す。
struct JSONValue;
JSON値ノード
const pure nothrow @nogc @property @safe JSONType type();
この構造体に格納されている値のJSONTypeを返す。
Examples:
string s = "{ \"language\": \"D\" }";
JSONValue j = parseJSON(s);
writeln(j.type); // JSONType.object
writeln(j["language"].type); // JSONType.string
const pure @property scope @trusted string str() return;

pure nothrow @nogc @property @trusted string str(return scope string v) return;
JSONType.string の値ゲッター/セッター。
Throws:
JSONException もし が .type JSONType.string
Examples:
JSONValue j = [ "language": "D" ];

// 値を取得する
writeln(j["language"].str); // "D"

// 既存のキーを新しい文字列に変更する
j["language"].str = "Perl";
writeln(j["language"].str); // "Perl"
const pure @property @safe long integer();

pure nothrow @nogc @property @safe long integer(long v);
の値ゲッター/セッター。 JSONType.integer.
Throws:
JSONException typeJSONType.integer.
const pure @property @safe ulong uinteger();

pure nothrow @nogc @property @safe ulong uinteger(ulong v);
の値ゲッター/セッター。 JSONType.uinteger.
Throws:
JSONException typeJSONType.uinteger.
const pure @property @safe double floating();

pure nothrow @nogc @property @safe double floating(double v);
JSONType.float_ の値ゲッター/セッター。名前にもかかわらず、これは -bitの 、32-bitの ではない。 名前にもかかわらず、これは64-bitdouble であり、32-bitfloat ではないことに注意。
Throws:
JSONException もし が .type JSONType.float_
const pure @property @safe bool boolean();

pure nothrow @nogc @property @safe bool boolean(bool v);
JSONに格納されたbooleanの値ゲッター/セッター。
Throws:
JSONException もし が または 。this.type JSONType.true_ JSONType.false_
Examples:
JSONValue j = true;
writeln(j.boolean); // true

j.boolean = false;
writeln(j.boolean); // false

j.integer = 12;
import std.exception : assertThrown;
assertThrown!JSONException(j.boolean);
inout pure @property ref @system inout(JSONValue[string]) object() return;

pure nothrow @nogc @property @trusted JSONValue[string] object(return scope JSONValue[string] v);
の値ゲッター/セッター。 JSONType.object.
Throws:
JSONException typeJSONType.object.

注釈:」である。 これは以下のパターンのため、@systemである:

auto a = &(json.object());
json.uinteger = 0;        // AAポインタを上書きする
(*a)["hello"] = "world";  // セグメンテーションフォールト

inout pure @property @trusted inout(JSONValue[string]) objectNoRef();
JSONType.object の値ゲッターである。 object とは異なり、これはオブジェクトを値で取得する。 でオブジェクトを取得し、"@safe" コードで使用できる。
注意点としては、返される値がNULLの場合、修正が見えなくなる、 の変更は見えなくなる:
JSONValue json;
json.object = null;
json.objectNoRef["hello"] = JSONValue("world");
assert("hello" !in json.object);
Throws:
JSONException type がない場合は、読み取りアクセスに使用する。 .JSONType.object
inout pure @property ref scope @system inout(JSONValue[]) array() return;

pure nothrow @nogc @property scope @trusted JSONValue[] array(return scope JSONValue[] v);
の値ゲッター/セッター。 JSONType.array.
Throws:
JSONException typeJSONType.array.

注釈:」である。 これは以下のパターンのため、@systemである:

auto a = &(json.array());
json.uinteger = 0;  // 配列ポインタを上書きする
(*a)[0] = "world";  // セグメンテーションフォールト

inout pure @property @trusted inout(JSONValue[]) arrayNoRef();
JSONType.array の"値"ゲッターである。 array とは異なり、これは値で配列を取得するので、@safeコードで使用できる。
注意点としては、返された配列に値を追加した場合、その新しい値は :: に表示されない、 新しい値はJSONValue では見えない:
JSONValue json;
json.array = [JSONValue("hello")];
json.arrayNoRef ~= JSONValue("world");
assert(json.array.length == 1);
Throws:
JSONException type がない場合は、読み取りアクセスに使用する。 .JSONType.array
const pure nothrow @nogc @property @safe bool isNull();
であるかどうかをテストする。JSONType.null_
inout const pure @property @safe inout(T) get(T)();

inout pure @property @trusted inout(T) get(T : JSONValue[string])();
このJSONValue を指定されたD型として返す便利なゲッターである。

注釈:数値型のみ受け付ける。 数値型、boolstringJSONValue[string]JSONValue[] の型のみが受け入れられる。

Throws:
JSONException T がこの内容を保持できない場合 に変換する際に整数がオーバーフローした場合、この内容を保持することができない。JSONValue ConvException T
Examples:
import std.exception;
import std.conv;
string s =
`{
    "a": 123,
    "b": 3.1415,
    "c": "text",
    "d": true,
    "e": [1, 2, 3],
    "f": { "a": 1 },
    "g": -45,
    "h": ` ~ ulong.max.to!string ~ `,
 }`;

struct a { }

immutable json = parseJSON(s);
writeln(json["a"].get!double); // 123.0
writeln(json["a"].get!int); // 123
writeln(json["a"].get!uint); // 123
writeln(json["b"].get!double); // 3.1415
assertThrown!JSONException(json["b"].get!int);
writeln(json["c"].get!string); // "text"
writeln(json["d"].get!bool); // true
assertNotThrown(json["e"].get!(JSONValue[]));
assertNotThrown(json["f"].get!(JSONValue[string]));
static assert(!__traits(compiles, json["a"].get!a));
assertThrown!JSONException(json["e"].get!float);
assertThrown!JSONException(json["d"].get!(JSONValue[string]));
assertThrown!JSONException(json["f"].get!(JSONValue[]));
writeln(json["g"].get!int); // -45
assertThrown!ConvException(json["g"].get!uint);
writeln(json["h"].get!ulong); // ulong.max
assertThrown!ConvException(json["h"].get!uint);
assertNotThrown(json["h"].get!float);
this(T)(T arg)
if (!isStaticArray!T);

this(T)(ref T arg)
if (isStaticArray!T);

inout this(T : JSONValue)(inout T arg);
JSONValue のコンストラクタである。もし argJSONValue であれば、その値と型が新しいJSONValue にコピーされる。 これは浅いコピーであることに注釈が必要である。JSONType.object またはJSONType.array の場合、データへの参照のみがコピーされる。 への参照だけがコピーされる。 そうでない場合は argであれば、データへの参照のみがコピーされる。 でなければならない:typeof(null) string,ulonglong double 、任意の連想配列V[K]V およびK すなわちJSONオブジェクト、任意の配列またはbool 。 型はそれに応じて設定される。
Examples:
JSONValue j = JSONValue( "a string" );
j = JSONValue(42);

j = JSONValue( [1, 2, 3] );
writeln(j.type); // JSONType.array

j = JSONValue( ["language": "D"] );
writeln(j.type); // JSONType.object
enum JSONValue emptyObject;
空のJSONオブジェクトを表すJSONValue 。 空のJSONオブジェクトを表す
Examples:
JSONValue obj1 = JSONValue.emptyObject;
writeln(obj1.type); // JSONType.object
obj1.object["a"] = JSONValue(1);
writeln(obj1.object["a"]); // JSONValue(1)

JSONValue obj2 = JSONValue.emptyObject;
assert("a" !in obj2.object);
obj2.object["b"] = JSONValue(5);
assert(obj1 != obj2);
enum JSONValue emptyArray;
空のJSON配列を表すJSONValue 。 空の JSON 配列を表す
Examples:
JSONValue arr1 = JSONValue.emptyArray;
writeln(arr1.type); // JSONType.array
writeln(arr1.array.length); // 0
arr1.array ~= JSONValue("Hello");
writeln(arr1.array.length); // 1
writeln(arr1.array[0]); // JSONValue("Hello")

JSONValue arr2 = JSONValue.emptyArray;
writeln(arr2.array.length); // 0
assert(arr1 != arr2);
inout pure ref @safe inout(JSONValue) opIndex(size_t i);
JSON配列の配列構文。
Throws:
JSONException if is not .type JSONType.array
Examples:
JSONValue j = JSONValue( [42, 43, 44] );
writeln(j[0].integer); // 42
writeln(j[1].integer); // 43
inout pure ref @safe inout(JSONValue) opIndex(return scope string k);
JSONオブジェクトのハッシュ構文。
Throws:
JSONException if is not .type JSONType.object
Examples:
JSONValue j = JSONValue( ["language": "D"] );
writeln(j["language"].str); // "D"
void opIndexAssign(T)(auto ref T value, string key);

void opIndexAssign(T)(T arg, size_t i);
インデックス割り当てのサポートを提供する。 インデックス割り当てのサポートを提供する。 keyフィールドの対応する値を value.
JSONValueJSONType.null_ の場合、この関数は、JSONオブジェクトでそれを初期化し、JSONオブジェクトのフィールドに対応する値を設定する。 である場合、この関数はJSONオブジェクトで初期化し、インデックス割り当てを実行する。 インデックス割り当てを実行する。
Throws:
JSONException type がそうでない場合 または である。JSONType.object JSONType.null_
Examples:
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
writeln(j["language"].str); // "Perl"
Examples:
JSONValue j = JSONValue( ["Perl", "C"] );
j[1].str = "D";
writeln(j[1].str); // "D"
inout @safe inout(JSONValue)* opBinaryRight(string op : "in")(string k);
in オペレーターをサポートする。
オブジェクトの中にキーがあるかどうかを調べる。
Returns:
見つかった場合、そのキーにマッチするinout(JSONValue)* 、 そうでない場合はnull
Throws:
JSONException 右辺の引数が が でない場合。JSONType object
Examples:
JSONValue j = [ "language": "D", "author": "walter" ];
string a = ("author" in j).str;
*("author" in j) = "Walter";
writeln(j["author"].str); // "Walter"
const pure nothrow @nogc @safe bool opEquals(const JSONValue rhs);

const pure nothrow @nogc @trusted bool opEquals(const ref JSONValue rhs);
Examples:
writeln(JSONValue(0u)); // JSONValue(0)
writeln(JSONValue(0u)); // JSONValue(0.0)
writeln(JSONValue(0)); // JSONValue(0.0)
@system int opApply(scope int delegate(size_t index, ref JSONValue) dg);
foreach opApplyインターフェイスを実装する。
@system int opApply(scope int delegate(string key, ref JSONValue) dg);
json オブジェクト用の foreach opApplyインターフェースを実装する。
const @safe string toString(in JSONOptions options = JSONOptions.none);
このJSONValueに対して暗黙的にtoJSON
オプションを使用して、変換動作を微調整できる。
const void toString(Out)(Out sink, in JSONOptions options = JSONOptions.none);
const @safe string toPrettyString(in JSONOptions options = JSONOptions.none);
toString のように、このJSONValueに対してtoJSON を暗黙的に呼び出す。 も、pretty引数としてtrueを渡す。
オプションを使用して、変換の動作を微調整することができる。
const void toPrettyString(Out)(Out sink, in JSONOptions options = JSONOptions.none);
JSONValue parseJSON(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none)
if (isSomeFiniteCharInputRange!T);
シリアライズされた文字列を解析し、JSON値のツリーを返す。
Throws:
JSONException文字列がJSONの文法に従っていないか、深さが最大深さを超えている場合、 ConvException入力の数値がネイティブのD型で表現できない場合。
Parameters:
T json 解析するJSON形式の文字列
int maxDepth 最大入れ子深さ、-1は深さチェックを無効にする。
JSONOptions options NaN/Infの文字列表現をfloat値としてデコードできるようにする。
JSONValue parseJSON(T)(T json, JSONOptions options)
if (isSomeFiniteCharInputRange!T);
直列化された文字列を解析し、JSON値のツリーを返す。
Throws:
JSONException深さが最大深さを超える場合
Parameters:
T json 解析するjson形式の文字列
JSONOptions options NaN/Infの文字列表現をfloat値としてデコードできるようにする。
@safe string toJSON(const ref JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none);
JSON値のツリーを受け取り、直列化された文字列を返す。
Object型はキーソートされた順序でシリアライズされる。
もし prettyがfalseの場合、空白は生成されない。 もし prettyがtrueの場合、直列化された文字列は人間が読めるようにフォーマットされる。 このフラグは JSONOptions.specialFloatLiteralsフラグが optionsにセットすると、NaN/Infinityを文字列としてエンコードする。
void toJSON(Out)(auto ref Out json, const ref JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none)
if (isOutputRange!(Out, char));
class JSONException: object.Exception;
JSONエラー時に例外がスローされる。