Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.json

Implements functionality to read and write JavaScript Object Notation values.
JavaScript Object Notation is a lightweight data interchange format commonly used in web services and configuration files.It's easy for humans to read and write, and it's easy for machines to parse and generate.
Warning: WhileJSONValue is fine for small-scale use, at the range of hundreds of megabytes it isknown to cause and exacerbate GC problems. If you encounter problems, try replacing it with a stream parser. Seealsohttps://forum.dlang.org/post/dzfyaxypmkdrpakmycjv@forum.dlang.org.
License:
Boost License 1.0.
Authors:
Jeremie Pelletier, David Herberth

Referenceshttp://json.org/,https://seriot.ch/projects/parsing_json.html

Sourcestd/json.d

Examples:
import std.conv : to;// parse a file or string of json into a usable structurestring s =`{ "language": "D", "rating": 3.5, "code": "42" }`;JSONValue j = parseJSON(s);// j and j["language"] return JSONValue,// j["language"].str returns a stringwriteln(j["language"].str);// "D"writeln(j["rating"].floating);// 3.5// check a typelong x;if (const(JSONValue)* code ="code"in j){if (code.type() == JSONType.integer)        x = code.integer;else        x = to!int(code.str);}// create a json structJSONValue jj = ["language":"D" ];// rating doesnt exist yet, so use .object to assignjj.object["rating"] = JSONValue(3.5);// create an array to assign to listjj.object["list"] = JSONValue( ["a","b","c"] );// list already exists, so .object optionaljj["list"].array ~= JSONValue("D");string jjStr =`{"language":"D","list":["a","b","c","D"],"rating":3.5}`;writeln(jj.toString);// jjStr
enumJSONFloatLiteral: string;
String literals used to represent special float values within JSON strings.
nan
String representation of floating-point NaN
inf
String representation of floating-point Infinity
negativeInf
String representation of floating-point negative Infinity
enumJSONOptions: int;
Flags that control how JSON is encoded and parsed.
none
Standard parsing and encoding
specialFloatLiterals
Encode NaN and Inf float values as strings
escapeNonAsciiChars
Encode non-ASCII characters with a Unicode escape sequence
doNotEscapeSlashes
Do not escape slashes ('/')
strictParsing
Strictly follow RFC-8259 grammar when parsing
preserveObjectOrder
Preserve order of object keys when parsing
enumJSONType: byte;
Enumeration of JSON types
null_

string

integer

uinteger

float_

array

object

true_

false_
Indicates the type of aJSONValue.
structJSONValue;
JSON value node
pure nothrow @nogc @property @safe JSONTypetype() const;
Returns the JSONType of the value stored in this structure.
Examples:
string s ="{ \"language\": \"D\" }";JSONValue j = parseJSON(s);writeln(j.type);// JSONType.objectwriteln(j["language"].type);// JSONType.string
pure @property @trusted stringstr() const return scope;

pure nothrow @nogc @property @trusted stringstr(return scope stringv) return;
Value getter/setter forJSONType.string.
Throws:
JSONException for read access iftype is notJSONType.string.
Examples:
JSONValue j = ["language":"D" ];// get valuewriteln(j["language"].str);// "D"// change existing key to new stringj["language"].str ="Perl";writeln(j["language"].str);// "Perl"
pure @property @safe longinteger() const;

pure nothrow @nogc @property @safe longinteger(longv);
Value getter/setter forJSONType.integer.
Throws:
JSONException for read access iftype is notJSONType.integer.
pure @property @safe ulonguinteger() const;

pure nothrow @nogc @property @safe ulonguinteger(ulongv);
Value getter/setter forJSONType.uinteger.
Throws:
JSONException for read access iftype is notJSONType.uinteger.
pure @property @safe doublefloating() const;

pure nothrow @nogc @property @safe doublefloating(doublev);
Value getter/setter forJSONType.float_. Note that despite the name, this is a64-bitdouble, not a 32-bitfloat.
Throws:
JSONException for read access iftype is notJSONType.float_.
pure @property @safe boolboolean() const;

pure nothrow @nogc @property @safe boolboolean(boolv);
Value getter/setter for boolean stored in JSON.
Throws:
JSONException for read access ifthis.type is notJSONType.true_ orJSONType.false_.
Examples:
JSONValue j =true;writeln(j.boolean);// truej.boolean =false;writeln(j.boolean);// falsej.integer = 12;import std.exception : assertThrown;assertThrown!JSONException(j.boolean);
pure @property ref @system inout(JSONValue[string])object() inout return;

pure nothrow @nogc @property @trusted JSONValue[string]object(return scope JSONValue[string]v);
Value getter/setter for unorderedJSONType.object.
Throws:
JSONException for read access iftype is notJSONType.object or the object is ordered.

Note This is @system because of the following pattern:

auto a = &(json.object());json.uinteger = 0;// overwrite AA pointer(*a)["hello"] ="world";// segmentation fault

pure @property @trusted inout(JSONValue[string])objectNoRef() inout;
Value getter for unorderedJSONType.object. Unlikeobject, this retrieves the object by value and can be used in @safe code.
One possible caveat is that, if the returned value is null, modifications will not be visible:
JSONValue json;json.object =null;json.objectNoRef["hello"] = JSONValue("world");assert("hello" !in json.object);
Throws:
JSONException for read access iftype is notJSONType.object.
pure @property ref @system inout(OrderedObjectMember[])orderedObject() inout return;

pure nothrow @nogc @property @trusted OrderedObjectMember[]orderedObject(return scope OrderedObjectMember[]v);
Value getter/setter for orderedJSONType.object.
Throws:
JSONException for read access iftype is notJSONType.object or the object is unordered.

Note This is @system because of the following pattern:

auto a = &(json.orderedObject());json.uinteger = 0;// overwrite AA pointer(*a)["hello"] ="world";// segmentation fault

pure @property @trusted inout(OrderedObjectMember[])orderedObjectNoRef() inout;
Value getter for orderedJSONType.object. UnlikeorderedObject, this retrieves the object by value and can be used in @safe code.
pure @property @trusted boolisOrdered() const;
Returnstrue if the order of keys of the represented object is being preserved.
pure @property ref @system inout(JSONValue[])array() inout scope return;

pure nothrow @nogc @property @trusted JSONValue[]array(return scope JSONValue[]v) scope;
Value getter/setter forJSONType.array.
Throws:
JSONException for read access iftype is notJSONType.array.

Note This is @system because of the following pattern:

auto a = &(json.array());json.uinteger = 0;// overwrite array pointer(*a)[0] ="world";// segmentation fault

pure @property @trusted inout(JSONValue[])arrayNoRef() inout;
Value getter forJSONType.array. Unlikearray, this retrieves the array by value and can be used in @safe code.
One possible caveat is that, if you append to the returned array, the new values aren't visible in theJSONValue:
JSONValue json;json.array = [JSONValue("hello")];json.arrayNoRef ~= JSONValue("world");assert(json.array.length == 1);
Throws:
JSONException for read access iftype is notJSONType.array.
pure nothrow @nogc @property @safe boolisNull() const;
Test whether the type isJSONType.null_
pure @property @safe inout(T)get(T)() inout const;

pure @property @trusted inout(T)get(T : JSONValue[string])() inout;
A convenience getter that returns thisJSONValue as the specified D type.

NoteOnly numeric types,bool,string,JSONValue[string], andJSONValue[] types are accepted

Throws:
JSONException ifT cannot hold the contents of thisJSONValueConvException in case of integer overflow when converting toT
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.0writeln(json["a"].get!int);// 123writeln(json["a"].get!uint);// 123writeln(json["b"].get!double);// 3.1415assertThrown!JSONException(json["b"].get!int);writeln(json["c"].get!string);// "text"writeln(json["d"].get!bool);// trueassertNotThrown(json["e"].get!(JSONValue[]));assertNotThrown(json["f"].get!(JSONValue[string]));staticassert(!__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);// -45assertThrown!ConvException(json["g"].get!uint);writeln(json["h"].get!ulong);// ulong.maxassertThrown!ConvException(json["h"].get!uint);assertNotThrown(json["h"].get!float);
this(T)(Targ)
if (!isStaticArray!T);

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

this(T : JSONValue)(inout Targ) inout;
Constructor forJSONValue. Ifarg is aJSONValue its value and type will be copied to the newJSONValue. Note that this is a shallow copy: if type isJSONType.object orJSONType.array then only the reference to the data will be copied. Otherwise,arg must be implicitly convertible to one of the following types:typeof(null),string,ulong,long,double, an associative arrayV[K] for anyV andK i.e. a JSON object, any array orbool. The type will be set accordingly.
Examples:
JSONValue j = JSONValue("a string" );j = JSONValue(42);j = JSONValue( [1, 2, 3] );writeln(j.type);// JSONType.arrayj = JSONValue( ["language":"D"] );writeln(j.type);// JSONType.object
enum JSONValueemptyObject;
An enum value that can be used to obtain aJSONValue representing an empty JSON object.
Examples:
JSONValue obj1 = JSONValue.emptyObject;writeln(obj1.type);// JSONType.objectobj1.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 JSONValueemptyOrderedObject;
An enum value that can be used to obtain aJSONValue representing an empty JSON object. UnlikeemptyObject, the order of inserted keys is preserved.
Examples:
JSONValue obj = JSONValue.emptyOrderedObject;writeln(obj.type);// JSONType.objectassert(obj.isOrdered);obj["b"] = JSONValue(2);obj["a"] = JSONValue(1);writeln(obj["a"]);// JSONValue(1)writeln(obj["b"]);// JSONValue(2)string[] keys;foreach (string k, JSONValue v; obj)    keys ~= k;writeln(keys);// ["b", "a"]
enum JSONValueemptyArray;
An enum value that can be used to obtain aJSONValue representing an empty JSON array.
Examples:
JSONValue arr1 = JSONValue.emptyArray;writeln(arr1.type);// JSONType.arraywriteln(arr1.array.length);// 0arr1.array ~= JSONValue("Hello");writeln(arr1.array.length);// 1writeln(arr1.array[0]);// JSONValue("Hello")JSONValue arr2 = JSONValue.emptyArray;writeln(arr2.array.length);// 0assert(arr1 != arr2);
pure ref @safe inout(JSONValue)opIndex(size_ti) inout;
Array syntax for JSON arrays.
Throws:
JSONException iftype is notJSONType.array.
Examples:
JSONValue j = JSONValue( [42, 43, 44] );writeln(j[0].integer);// 42writeln(j[1].integer);// 43
pure ref @safe inout(JSONValue)opIndex(return scope stringk) inout;
Hash syntax for JSON objects.
Throws:
JSONException iftype is notJSONType.object.
Examples:
JSONValue j = JSONValue( ["language":"D"] );writeln(j["language"].str);// "D"
voidopIndexAssign(T)(auto ref Tvalue, stringkey);

voidopIndexAssign(T)(Targ, size_ti);
Provides support for index assignments, which sets the corresponding value of the JSON object'skey field tovalue.
If theJSONValue isJSONType.null_, then this function initializes it with a JSON object and then performs the index assignment.
Throws:
JSONException iftype is notJSONType.object orJSONType.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"
@safe inout(JSONValue)*opBinaryRight(string op : "in")(stringk) inout;
Provides support for thein operator.
Tests whether a key can be found in an object.
Returns:
When found, theinout(JSONValue)* that matches to the key, otherwisenull.
Throws:
JSONException if the right hand side argumentJSONType is notobject.
Examples:
JSONValue j = ["language":"D","author":"walter" ];string a = ("author"in j).str;*("author"in j) ="Walter";writeln(j["author"].str);// "Walter"
pure nothrow @nogc @safe boolopEquals(const JSONValuerhs) const;

pure nothrow @nogc @trusted boolopEquals(ref const JSONValuerhs) const;
Compare two JSONValues for equality
JSON arrays and objects are compared deeply. The order of object keys does not matter.
Floating point numbers are compared for exact equality, not approximal equality.
Different number types (unsigned, signed, and floating) will be compared by converting them to a common type, in the same way that comparison of built-in Dint,uint andfloat works.
Other than that, types must match exactly. Empty arrays are not equal to empty objects, and booleans are never equal to integers.
Returns:
whether thisJSONValue is equal torhs
pure nothrow @nogc @trusted hash_ttoHash() const;
Calculate a numerical hash value for this value,allowingJSONValue to be used in associative arrays.
Examples:
assert(JSONValue(10).opEquals(JSONValue(10.0)));assert(JSONValue(10) != (JSONValue(10.5)));assert(JSONValue(1) != JSONValue(true));assert(JSONValue.emptyArray != JSONValue.emptyObject);assert(parseJSON(`{"a": 1, "b": 2}`).opEquals(parseJSON(`{"b": 2, "a": 1}`)));
@system intopApply(scope int delegate(size_t index, ref JSONValue)dg);
Implements the foreachopApply interface for json arrays.
@system intopApply(scope int delegate(string key, ref JSONValue)dg);
Implements the foreachopApply interface for json objects.
@safe stringtoString(in JSONOptionsoptions = JSONOptions.none) const;
Implicitly callstoJSON on this JSONValue.
options can be used to tweak the conversion behavior.
voidtoString(Out)(Outsink, in JSONOptionsoptions = JSONOptions.none) const;
@safe stringtoPrettyString(in JSONOptionsoptions = JSONOptions.none) const;
Implicitly callstoJSON on this JSONValue, liketoString, but also passestrue aspretty argument.
options can be used to tweak the conversion behavior
voidtoPrettyString(Out)(Outsink, in JSONOptionsoptions = JSONOptions.none) const;
JSONValueparseJSON(T)(Tjson, intmaxDepth = -1, JSONOptionsoptions = JSONOptions.none)
if (isSomeFiniteCharInputRange!T);
Parses a serialized string and returns a tree of JSON values.
Throws:
JSONException if string does not follow the JSON grammar or the depth exceeds the max depth,ConvException if a number in the input cannot be represented by a native D type.
Parameters:
Tjsonjson-formatted string to parse
intmaxDepthmaximum depth of nesting allowed, -1 disables depth checking
JSONOptionsoptionsenable decoding string representations of NaN/Inf as float values
JSONValueparseJSON(T)(Tjson, JSONOptionsoptions)
if (isSomeFiniteCharInputRange!T);
Parses a serialized string and returns a tree of JSON values.
Throws:
JSONException if the depth exceeds the max depth.
Parameters:
Tjsonjson-formatted string to parse
JSONOptionsoptionsenable decoding string representations of NaN/Inf as float values
@safe stringtoJSON(ref const JSONValueroot, in boolpretty = false, in JSONOptionsoptions = JSONOptions.none);
Takes a tree of JSON values and returns the serialized string.
Any Object types will be serialized in a key-sorted order.
Ifpretty is false no whitespaces are generated.Ifpretty is true serialized string is formatted to be human-readable.Set theJSONOptions.specialFloatLiterals flag is set inoptions to encode NaN/Infinity as strings.
voidtoJSON(Out)(auto ref Outjson, ref const JSONValueroot, in boolpretty = false, in JSONOptionsoptions = JSONOptions.none)
if (isOutputRange!(Out, char));
classJSONException:object.Exception;
Exception thrown on JSON errors
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Sat Feb 21 04:08:01 2026

[8]ページ先頭

©2009-2026 Movatter.jp