Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
Select your favorite languages :
  • Or search :

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)
(require '[clojure.java.io :refer [file]])
(require '[jsonista.core :refer [read-value]])
(def x (read-value (file "data.json")))
using System.IO;
using Newtonsoft.Json.Linq;
JObject x = JObject.Parse(File.ReadAllText("data.json"));
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(new File('data.json').readAsStringSync());
import 'dart:io' show File;
import 'dart:convert' show json;
Map x = json.jsonDecode(await new File('data.json').readAsString());
import "encoding/json"
r, err := os.Open(filename)
if err != nil {
	return err
}
decoder := json.NewDecoder(r)
err = decoder.Decode(&x)
if err != nil {
	return err
}
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
}
const fs = require('fs');
const x = JSON.parse(fs.readFileSync('./data.json'));
const x = require('./data.json');
$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")?)?;

New implementation...
programming-idioms.org