在 Go 中正确解析 JSON

Parse JSON correctly in Go

从最近 2 天开始,我不知何故坚持使用 JSON 和 Go。我的目标很简单,一个 Go 程序可以读取 JSON 文件,正确输出并向 JSON 添加一些项目,然后将其重写回磁盘。

已保存 JSON 个文件。

{
"Category": ["food","music"],
"Time(min)": "351",
"Channel": {
    "d2d": 10,
    "mkbhd": 8,
    "coding Train": 24
},
"Info": {
    "Date":{
        "date":["vid_id1","vid_id2","vid_id3"],
        "02/11/2019":["id1","id2","id3"],
        "03/11/2019":["SonwZ6MF5BE","8mP5xOg7ijs","sc2ysHjSaXU"]
        },
    "Videos":{
        "videos": ["Title","Category","Channel","length"],
        "sc2ysHjSaXU":["Bob Marley - as melhores - so saudade","Music","So Saudade","82"],
        "SonwZ6MF5BE":["Golang REST API With Mux","Science & Technology","Traversy Media","44"],
        "8mP5xOg7ijs":["Top 15 Funniest Friends Moments","Entertainment","DjLj11","61"]
    }
  }
}

我已经在 Go 中成功解析了 JSON,但是当我尝试获取 JSON["Info"]["Date"] 时,它会抛出接口错误。我无法制作特定的结构,因为只要 code/API 被调用,所有项目都会动态更改。

我用来解析数据的代码

// Open our jsonFile
jsonFile, err := os.Open("yt.json")
if err != nil {fmt.Println(err)}
fmt.Println("Successfully Opened yt.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var result map[string]interface{}
json.Unmarshal([]byte(byteValue), &result)


json_data := result["Category"] //returns correct ans
json_data := result["Info"]["Date"] // returns error - type interface {} does not support indexing

任何 help/lead 非常感谢。非常感谢。

不幸的是,每次访问解析后的数据时都必须断言类型:

date := result["Info"].(map[string]interface{})["Date"]

现在 datemap[string]interface{},但它的静态已知类型仍然是 interface{}

这意味着您要么需要提前假定类型,要么需要某种类型的 type switch 如果结构可能会有所不同。

您无法使用 result[][] 访问内部属性。你需要做如下的事情,

info:= result["Info"]
v := info.(map[string]interface{})
json_data = v["Date"]