go读取json数组文件

test.json格式如下

[{
"connection": "488.0",
"name": "xxx",
 "region_ip": "10.28.78.122", 
 "region_name": "xxx",
 "time": "2021-02-01 16:17:00.000", 
 "__source__": "",
 "__time__": "1610871517"
},
{
"connection": "488.0",
"name": "xxx",
 "region_ip": "10.28.78.122", 
 "region_name": "xxx",
 "time": "2021-02-01 16:17:00.000", 
 "__source__": "",
 "__time__": "1610871517"
}]

在于定义结构体数组来接受json数组的值


package main
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)
// Ignore the unused imports.
type Logdata struct {
	Connection string `json:connection`
	Name string	`json:name`
	Region_ip string `json:region_ip`
	Region_name string `json:region_name`
	Time string `json:time`
	Source string `json:source,omitempty`
	Time_chuo string `json:time_chuo`
}
func getConfigs() string {


	b, err := ioutil.ReadFile("test.json") // just pass the file name


	if err != nil {
		fmt.Print(err)
	}


	str := string(b) // convert content to a 'string'
	fmt.Println(str) // print the content as a 'string'
	return str
}
func deserializeJson(configJson string) []Logdata {


	jsonAsBytes := []byte(configJson)
	configs := make([]Logdata, 0)
	err := json.Unmarshal(jsonAsBytes, &configs)
	fmt.Printf("%#v", configs)
	if err != nil {
		panic(err)
	}
	return configs
}
func main() {

	// Unmarshal each fastDeploy config component into a slice of structs.
	jsonConfigList := getConfigs()
	unmarshelledConfigs := deserializeJson(jsonConfigList)
	for _, configObj := range unmarshelledConfigs {
		fmt.Printf("Connection: %s Name: %d", configObj.Connection, configObj.Name)
	}
}

你可能感兴趣的:(go,json,golang)