Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • D

Idiom #91 Load JSON file into object

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

import std.file: readText;
import std.json: parseJSon;
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);

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.
(require '[clojure.java.io :refer [file]])
(require '[jsonista.core :refer [read-value]])
(def x (read-value (file "data.json")))

New implementation...