Last active
December 14, 2015 18:59
-
-
Save physacco/5133595 to your computer and use it in GitHub Desktop.
Test the JSON decoder in go's stdlib by parsing package.json of a nodejs project.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"fmt" | |
"encoding/json" | |
) | |
type PackageInfo struct { | |
Name string | |
Main string | |
Version string | |
License string | |
Description string | |
} | |
func (info PackageInfo) String() (str string) { | |
str += "<PackageInfo " | |
str += "Name: " + info.Name | |
str += ", Main: " + info.Main | |
str += ", Version: " + info.Version | |
str += ", License: " + info.License | |
str += ", Description: " + info.Description | |
str += ">" | |
return | |
} | |
func main() { | |
file, err := os.Open("package.json") | |
if err != nil { | |
panic(err) | |
} | |
defer file.Close() | |
dec := json.NewDecoder(file) | |
var res map[string]interface{} | |
if err := dec.Decode(&res); err != nil { | |
panic(err) | |
} | |
var info PackageInfo | |
for k, v := range res { | |
switch v.(type) { | |
case int: | |
fmt.Printf("%s : int => %s\n\n", k, v) | |
case string: | |
fmt.Printf("%s : string => %s\n\n", k, v) | |
vs := v.(string) | |
switch k { | |
case "name": | |
info.Name = vs | |
case "main": | |
info.Main = vs | |
case "version": | |
info.Version = vs | |
case "license": | |
info.License = vs | |
case "description": | |
info.Description = vs | |
} | |
case []interface{}: | |
fmt.Printf("%s : array => %s\n\n", k, v) | |
case map[string]interface{}: | |
fmt.Printf("%s : map\n", k) | |
if x, ok := v.(map[string]interface{}); ok { | |
for kk, vv := range x { | |
fmt.Printf(" %s => %s\n", kk, vv) | |
} | |
fmt.Println() | |
} | |
default: | |
fmt.Println(k, ": unknown type") | |
} | |
} | |
fmt.Println(info) | |
} | |
// Refer to: http://golang.org/doc/articles/json_and_go.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment