Part 005 Reading In JSON Data Into An Interface For The Template

We can read in a JSON file for the data. One way of doing this is to read the JSON data into a set of typed structures. That has the advantage of type-checking the JSON data. The other way is to read the JSON into an interface{}. This provides a very flexible solution. We will get back to reading JSON into structs later.

An example (ex5.go):

package main

// (C) Philip Schlump, 2013.
// MIT Licensed, see LICENSE.txt

// -----------------------------------------------------------------------------
// Read JSON into a map of interface, then read in Template then process it
// -----------------------------------------------------------------------------

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"text/template"
)

func readInFile(path string) string {
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return ""
	}
	return string(file)
}

func readInJson(path string) map[string]interface{} {
	var jsonData map[string]interface{}
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return jsonData
	}
	json.Unmarshal(file, &jsonData)
	return jsonData
}

func main() {
	tmpl := readInFile("ex4.tmpl")

	person := readInJson("ex5.json")

	t := template.New("file-template")
	t, err := t.Parse(tmpl)
	if err != nil {
		panic(err)
		os.Exit(1)
	}

	err = t.ExecuteTemplate(os.Stdout, "file-template", person)
	if err != nil {
		panic(err)
		os.Exit(1)
	}
}


To run this you can

$ go run ex5.go


To compile it and run it

$ go build ex5.go
$ ./ex5

The output you should expect from running it is (ex5.out):


My name is: Philip J. Schlump.



Code tested on: Ubuntu 12.04, Mac 10.8, Windows 7 in go 1.1.2


•       •       •       •       •       •

Summary: # of Words: 201
Author: Philip J. Schlump
Published On: 2013-10-23

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens