JSONParser

Struct for parsing JSON.

Constructors

this
this()
Undocumented in source.
this
this(T input)

Start parsing using the given object, converting it to an InputRange.

Members

Enums

Type
enum Type

Type of a JSON value

Functions

getArray
auto getArray()

Get array elements by iterating over them.

getArray
T[] getArray()

Get an array of elements matching the type.

getArray
T getArray()

Get a static array of elements matching the type.

getArray
Element[Size] getArray()

Get a static array of elements matching the types.

getAssoc
T[wstring] getAssoc()

Get an associative array from the JSON.

getBoolean
bool getBoolean()

Get a boolean and skip to the next value.

getNull
void getNull()

Expect the next value to be null and skip to the next value.

getNumber
T getNumber()

Get the next number.

getObject
auto getObject()

Get object contents by iterating over them.

getString
wstring getString()

Get the next string.

getStruct
T getStruct(void delegate(ref T, wstring) fallback)

Push object contents into a struct or class.

peekType
Type peekType()

Check the next type in the document.

save
JSONParser save()

Copy the parser. Useful to keep document data for later.

skipValue
void skipValue()

Skip the next value in the JSON.

updateStruct
T updateStruct(T obj, void delegate(ref T, wstring) fallback)

Push object contents into a struct or class.

Templates

get
template get(T)

Get a value of the matching type.

Variables

input
ForwardRange!dchar input;

Input taken by the parser.

lineNumber
size_t lineNumber;

Current line number.

Examples

auto json = JSONParser(q{
    [
        {
            "name": "John",
            "surname": "Doe",
            "age": 42
        },
        {
            "name": "Jane",
            "surname": "Doe",
            "age": 46
        }
    ]
});

// Check each array item
foreach (index; json.getArray) {

    // Read the object
    auto keys = json.getObject;

    // Check the name
    assert(keys.front == "name");
    json.skipValue();
    keys.popFront();

    // Surname
    assert(keys.front == "surname");
    assert(json.getString == "Doe");
    keys.popFront();

    // Age
    assert(keys.front == "age");
    assert(json.getNumber!uint > 40);
    keys.popFront();

    // Done
    assert(keys.empty);

}

Moving to struct with a helper

struct Person {

    string name;
    string surname;
    uint age;

}

auto json = JSONParser(q{
    [
        {
            "name": "John",
            "surname": "Doe",
            "age": 42
        },
        {
            "name": "Jane",
            "surname": "Doe",
            "age": 46
        }
    ]
});

auto people = json.getArray!Person;

assert(people[0].name == "John");
assert(people[1].name == "Jane");
assert(people[0].age == 42);
assert(people[1].age == 46);

Meta