Part 006 Reading JSON Data And Templates In Go Using The Command Line

This time we take the names of the template file and the JSON data from the command line. This will allow us to quickly experiment with the templates and see how they interact with our JSON data.

An example (ex6.go):

package main

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

// Take file names from the command line

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"os"
)

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() {

	if len(os.Args) != 3 {
		fmt.Printf("Usage: ex6 TemplateFileName Data.JSON\n")
		os.Exit(1)
	}

	var tmpl_fn string = os.Args[1]
	var data_fn string = os.Args[2]

	tmpl := readInFile(tmpl_fn)
	person := readInJson(data_fn)

	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 ex6.go ex4.tmpl ex5.json


To compile it and run it

$ go build ex6.go
$ ./ex6 ex4.tmpl ex5.json

The output you should expect from running it is (ex6.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: 153
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