Skip to content

Instantly share code, notes, and snippets.

@bjdean
Last active December 18, 2015 03:48
Show Gist options
  • Save bjdean/5720290 to your computer and use it in GitHub Desktop.
Save bjdean/5720290 to your computer and use it in GitHub Desktop.
Google Go - Playing around with JSON
{
"a" : "a is for apple",
"b" : ["b", "is", "a", "list"],
"c" : {
"d" : "dog",
"e" : "elephant",
"f" : "frog"
}
}
/*
Playing around with JSON
Bug - or something - the structs only seem to pick up
data if they are in CamelCase. Lower-case slot names
are completely ignored (the docs sugges that mathcing case
is preferred, this is not correct)
*/
package main
import (
"os"
"encoding/json"
"fmt"
)
// Define the data structure allowed to arrive via JSON
type InputData struct {
A string
B []string
C SubInputData
}
type SubInputData struct {
D, E, F string
}
func main () {
jsonFile := os.Args[1]
jsonFh, jsonFhErr := os.Open(jsonFile)
if jsonFhErr != nil { panic(jsonFhErr) }
fhStat, fhStatErr := jsonFh.Stat()
if fhStatErr != nil { panic(fhStatErr) }
json_bytes := make( []byte, fhStat.Size() )
_, read_err := jsonFh.Read(json_bytes)
if read_err != nil { panic(read_err) }
jsonFh.Close()
var myData InputData
unmarshalErr := json.Unmarshal(json_bytes, &myData)
if unmarshalErr != nil { panic(unmarshalErr) }
fmt.Printf("%+v\n", myData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment