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

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.

import json
with open("data.json", "r") as input:
    x = json.load(input)
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);
import 'dart:io' show File;
import 'dart:convert' show json;
Map x = json.jsonDecode(await new File('data.json').readAsString());
import "encoding/json"
import "io/ioutil"
buffer, err := ioutil.ReadFile("data.json")
if err != nil {
	return err
}
err = json.Unmarshal(buffer, &x)
if err != nil {
	return err
}
$x = json_decode(file_get_contents('data.json'));
use File::Slurp;
use JSON;
my $str = read_file('data.json');
my $x = decode_json($str);
require 'json'
x = JSON.parse(File.read('data.json'))
#[macro_use] extern crate serde_derive;
extern crate serde_json;
use std::fs::File;
let x = ::serde_json::from_reader(File::open("data.json"))?;

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms