golang 引用json文件并存入变量
可以使用Go语言内置的encoding/json包来引用JSON文件并将其存入变量中。
首先,需要定义一个结构体来表示JSON文件中的数据结构。例如,假设JSON文件的内容如下:
{
"name": "Alice",
"age": 25,
"address": {
"city": "New York",
"state": "NY"
}
}
则可以定义如下结构体:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address struct {
City string `json:"city"`
State string `json:"state"`
} `json:"address"`
}
接下来,可以使用json.Unmarshal()函数来读取JSON文件并将其解码为结构体变量。例如,假设JSON文件名为data.json,则可以使用以下代码:
import (
"encoding/json"
"os"
)
func main() {
file, err := os.Open("data.json")
if err != nil {
panic(err)
}
defer file.Close()
var person Person
err = json.NewDecoder(file).Decode(&person)
if err != nil {
panic(err)
}
// person 变量现在包含了 JSON 文件中的数据
fmt.Printf("Name: %s\n", person.Name)
fmt.Printf("Age: %d\n", person.Age)
fmt.Printf("City: %s\n", person.Address.City)
fmt.Printf("State: %s\n", person.Address.State)
}
在上述代码中,json.NewDecoder()函数返回一个Decoder类型的值,它可以从文件中读取JSON数据并解码为指定的结构体类型。调用Decode()方法时需要传入一个指向结构体变量的指针,该方法将修改该指针指向的变量并返回错误信息(如果有的话)。
最后,可以使用结构体变量中的数据进行任何需要的操作
原文地址: https://www.cveoy.top/t/topic/fU0b 著作权归作者所有。请勿转载和采集!