在本教程之后,我将尝试在Golang中读取一个json文件。它说有两种方法可以做到这一点:
- 使用一组预定义的结构来解组JSON
- 或使用map[string]接口对JSON进行解组{}
因为我可能会有很多不同的json格式,所以我更喜欢动态地解释它。所以我现在有了以下代码:
package main
import (
"fmt"
"os"
"io/ioutil"
"encoding/json"
)
func main() {
// Open our jsonFile
jsonFile, err := os.Open("users.json")
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened users.json")
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var result map[string]interface{}
json.Unmarshal([]byte(byteValue), &result)
fmt.Println(result["users"])
fmt.Printf("%Tn", result["users"])
}
打印出来:
Successfully Opened users.json
[map[type:Reader age:23 social:map[facebook:https://facebook.com twitter:https://twitter.com] name:Elliot] map[name:Fraser type:Author age:17 social:map[facebook:https://facebook.com twitter:https://twitter.com]]]
[]interface {}
在这一点上,我不明白如何读取第一个用户(23岁(的年龄。我尝试了一些变体:
fmt.Println(result["users"][0])
fmt.Println(result["users"][0].age)
但显然,type interface {} does not support indexing
。
有没有一种方法可以在不定义结构的情况下访问json中的项?
您可能想要
fmt.Println(result["users"].(map[string]interface{})["age"])
或
fmt.Println(result[0].(map[string]interface{})["age"])
由于JSON是映射的映射,叶节点的类型是接口{},因此必须转换为map[string]接口{}才能查找密钥
定义结构要容易得多。我做这件事的首要技巧是使用一个将JSON转换为Go结构定义的网站,比如JSON to Go