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 using
a 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: While JSONValue is fine for small-scale use, at the range of hundreds of megabytes it is
known to cause and exacerbate GC problems. If you encounter problems, try replacing it with a stream parser. See
also https://forum.dlang.org/post/dzfyaxypmkdrpakmycjv@forum.dlang.org.
License:
Authors:
Jeremie Pelletier, David Herberth
References http://json.org/, http://seriot.ch/parsing_json.html
Source std/json.d
Examples:
import std.conv : to; // parse a file or string of json into a usable structure string s = `{ "language": "D", "rating": 3.5, "code": "42" }`; JSONValue j = parseJSON(s); // j and j["language"] return JSONValue, // j["language"].str returns a string writeln(j["language"].str); // "D" writeln(j["rating"].floating); // 3.5 // check a type long 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 struct JSONValue jj = [ "language": "D" ]; // rating doesnt exist yet, so use .object to assign jj.object["rating"] = JSONValue(3.5); // create an array to assign to list jj.object["list"] = JSONValue( ["a", "b", "c"] ); // list already exists, so .object optional jj["list"].array ~= JSONValue("D"); string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`; writeln(jj.toString); // jjStr
- enum
JSONFloatLiteral
: 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
- enum
JSONOptions
: 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
- enum
JSONType
: byte; - Enumeration of JSON types
null_
string
integer
uinteger
float_
array
object
true_
false_
- Indicates the type of a JSONValue.
- struct
JSONValue
; - JSON value node
- const pure nothrow @nogc @property @safe JSONType
type
(); - Returns the JSONType of the value stored in this structure.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 stringstr
(return scope stringv
) return; - Value getter/setter for JSONType.string.Throws:JSONException for read access if type is not JSONType.string.Examples:
JSONValue j = [ "language": "D" ]; // get value writeln(j["language"].str); // "D" // change existing key to new string j["language"].str = "Perl"; writeln(j["language"].str); // "Perl"
- const pure @property @safe long
integer
();
pure nothrow @nogc @property @safe longinteger
(longv
); - Value getter/setter for JSONType.
integer
.Throws:JSONException for read access if type is not JSONType.integer
. - const pure @property @safe ulong
uinteger
();
pure nothrow @nogc @property @safe ulonguinteger
(ulongv
); - Value getter/setter for JSONType.
uinteger
.Throws:JSONException for read access if type is not JSONType.uinteger
. - const pure @property @safe double
floating
();
pure nothrow @nogc @property @safe doublefloating
(doublev
); - Value getter/setter for JSONType.float_. Note that despite the name, this is a 64-bit double, not a 32-bit float.Throws:JSONException for read access if type is not JSONType.float_.
- const pure @property @safe bool
boolean
();
pure nothrow @nogc @property @safe boolboolean
(boolv
); - Value getter/setter for boolean stored in JSON.Throws:JSONException for read access if this.type is not JSONType.true_ or 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
); - Value getter/setter for JSONType.
object
.Throws:JSONException for read access if type is not JSONType.object
.Note This is @system because of the following pattern:
auto a = &(json.object()); json.uinteger = 0; // overwrite AA pointer (*a)["hello"] = "world"; // segmentation fault
- inout pure @property @trusted inout(JSONValue[string])
objectNoRef
(); - Value getter for JSONType.object. Unlike object, 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 if type is not JSONType.object. - inout pure @property ref scope @system inout(JSONValue[])
array
() return;
pure nothrow @nogc @property scope @trusted JSONValue[]array
(return scope JSONValue[]v
); - Value getter/setter for JSONType.
array
.Throws:JSONException for read access if type is not JSONType.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
- inout pure @property @trusted inout(JSONValue[])
arrayNoRef
(); - Value getter for JSONType.array. Unlike array, 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 the JSONValue:
JSONValue json; json.array = [JSONValue("hello")]; json.arrayNoRef ~= JSONValue("world"); assert(json.array.length == 1);
Throws:JSONException for read access if type is not JSONType.array. - const pure nothrow @nogc @property @safe bool
isNull
(); - Test whether the type is JSONType.null_
- inout const pure @property @safe inout(T)
get
(T)();
inout pure @property @trusted inout(T)get
(T : JSONValue[string])(); - A convenience getter that returns this JSONValue as the specified D type.
Note Only numeric types, bool, string, JSONValue[string], and JSONValue[] types are accepted
Throws:JSONException if T cannot hold the contents of this JSONValue ConvException in case of integer overflow when converting to TExamples: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 Targ
)
if (isStaticArray!T);
inout this(T : JSONValue)(inout Targ
); - Constructor for JSONValue. If
arg
is a JSONValue its value and type will be copied to the new JSONValue. Note that this is a shallow copy: if type is JSONType.object or JSONType.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 array V[K] for any V and K i.e. a JSON object, any array or bool. The type will be set accordingly.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
; - An enum value that can be used to obtain a JSONValue representing an empty JSON object.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
; - An enum value that can be used to obtain a JSONValue representing an empty JSON array.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_ti
); - Array syntax for JSON arrays.Throws:JSONException if type is not 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 stringk
); - Hash syntax for JSON objects.Throws:JSONException if type is not JSONType.object.Examples:
JSONValue j = JSONValue( ["language": "D"] ); writeln(j["language"].str); // "D"
- void
opIndexAssign
(T)(auto ref Tvalue
, stringkey
);
voidopIndexAssign
(T)(Targ
, size_ti
); - Provides support for index assignments, which sets the corresponding value of the JSON object's
key
field tovalue
.If the JSONValue is JSONType.null_, then this function initializes it with a JSON object and then performs the index assignment.Throws:JSONException if type is not JSONType.object or 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")(stringk
); - Provides support for the in operator.Tests whether a key can be found in an object.Returns:When found, the inout(JSONValue)* that matches to the key, otherwise null.Throws:JSONException if the right hand side argument JSONType is not 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 JSONValuerhs
);
const pure nothrow @nogc @trusted boolopEquals
(const ref JSONValuerhs
); - 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
); - Implements the foreach
opApply
interface for json arrays. - @system int
opApply
(scope int delegate(string key, ref JSONValue)dg
); - Implements the foreach
opApply
interface for json objects. - const @safe string
toString
(in JSONOptionsoptions
= JSONOptions.none); - Implicitly calls toJSON on this JSONValue.options can be used to tweak the conversion behavior.
- const void
toString
(Out)(Outsink
, in JSONOptionsoptions
= JSONOptions.none); - const @safe string
toPrettyString
(in JSONOptionsoptions
= JSONOptions.none); - Implicitly calls toJSON on this JSONValue, like toString, but also passes true as pretty argument.options can be used to tweak the conversion behavior
- const void
toPrettyString
(Out)(Outsink
, in JSONOptionsoptions
= JSONOptions.none);
- JSONValue
parseJSON
(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:
T json
json-formatted string to parse int maxDepth
maximum depth of nesting allowed, -1 disables depth checking JSONOptions options
enable decoding string representations of NaN/Inf as float values - JSONValue
parseJSON
(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:
T json
json-formatted string to parse JSONOptions options
enable decoding string representations of NaN/Inf as float values - @safe string
toJSON
(const ref 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. If
pretty
is false no whitespaces are generated. Ifpretty
is true serialized string is formatted to be human-readable. Set the JSONOptions.specialFloatLiterals flag is set inoptions
to encode NaN/Infinity as strings. - void
toJSON
(Out)(auto ref Outjson
, const ref JSONValueroot
, in boolpretty
= false, in JSONOptionsoptions
= JSONOptions.none)
if (isOutputRange!(Out, char)); - class
JSONException
: object.Exception; - Exception thrown on JSON errors
Copyright © 1999-2024 by the D Language Foundation | Page generated by
Ddoc on Sun Nov 17 01:08:36 2024