Logo

Programming-Idioms

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

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 "encoding/json"
import "os"
buffer, err := os.ReadFile("data.json")
if err != nil {
	return err
}
err = json.Unmarshal(buffer, &x)
if err != nil {
	return err
}

buffer is a []byte.
&x is the address of x.
You must check errors after each step.
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
}

Create and use a *json.Decoder
(require '[clojure.java.io :refer [file]])
(require '[jsonista.core :refer [read-value]])
(def x (read-value (file "data.json")))

New implementation...