Logo

Programming-Idioms

  • Lua
  • Pascal
  • Rust
  • C
  • Python

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 json
with open("data.json", "r") as input:
    x = json.load(input)
cjson = require("cjson")
file = io.open("data.json")
x = cjson.decode(file:read("a"))
file:close()

The "a" parameter means "all" - read entire file.
#[macro_use] extern crate serde_derive;
extern crate serde_json;
use std::fs::File;
let x = ::serde_json::from_reader(File::open("data.json")?)?;

Requires x implements Deserialize from serde.
Serde is used to create an object from data, rather than populate an existing object.
(require '[clojure.java.io :refer [file]])
(require '[jsonista.core :refer [read-value]])
(def x (read-value (file "data.json")))

New implementation...