Logo

Programming-Idioms

History of Idiom 91 > diff from v10 to v11

Edit summary for version 11 by :

Version 10

2015-11-04, 00:44:59

Version 11

2015-11-04, 00:46:43

Idiom #91 Load JSON file into struct

Read from file data.json and write its content into object x.
Assume the JSON data is suitable for the type of x.

Idiom #91 Load JSON file into struct

Read from file data.json and write its content into object x.
Assume the JSON data is suitable for the type of x.

Imports
import std.file: readText;
import std.json: parseJSon;
Imports
import std.file: readText;
import std.json: parseJSon;
Code
JSONValue x = "data.json".readText.parseJSON;

// We could use x as it is, but if we want to fill a structure
// the best is to define a constructor taking the JSONValue
struct User {
    int age;
    string name;

    this(JSONValue user) {
        age  = user["age"];
        name = user["name"];
    }
}

auto user = User(x);
Code
JSONValue x = "data.json".readText.parseJSON;

struct User {
    int age;
    string name;

    this(JSONValue user) {
        age  = user["age"];
        name = user["name"];
    }
}

auto user = User(x);
Comments bubble
We could use the JSONValue x as it is, but if we want to fill a given structure the best is to define a specific constructor.
Doc URL
http://dlang.org/phobos/std_json.html#.parseJSON
Doc URL
http://dlang.org/phobos/std_json.html#.parseJSON