golang解析json文件

* gopher.json

{
    "name": "Gopher",
    "title": "programmer",
    "contact": {
	"home":"415.333.3333",
	"cell":"415.555.5555"
    }
}

 

* gopher.go

package main

import (
	"encoding/json"
	"fmt"
//	"log"
//	"net/http"
	"os"
	"io/ioutil"
)

type Contact struct {
	Name string `json:"name"`
	Title string `json:"title"`
	Contact struct {
		Home string `json:"home"`
		Cell string `json:"cell"`
	} `json:"contact"`
}

func file_get_contents(path string) ([]byte, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(f)
}

func main() {
	var c Contact
	var content []byte
	var err error
	
	content, err = file_get_contents("gopher.json")
	if err != nil {
		fmt.Println("open file error: "+ err.Error())
		return
	}
	err = json.Unmarshal([]byte(content), &c)
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		return
	}
	fmt.Println(c)
	fmt.Println(c.Contact.Home)
}

* test:

go run gopher.go

{Gopher programmer {415.333.3333 415.555.5555}}
415.333.3333
 

 

你可能感兴趣的:(golang)