在Go中正确解析JSON

问题描述 投票:0回答: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”]时,它将引发接口错误。我无法建立特定的结构,因为只要调用代码/ 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

非常感谢任何帮助/领导。非常感谢。

json go marshalling unmarshalling
2个回答
0
投票

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

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

现在datemap[string]interface{},但其静态已知类型仍为interface{}

这意味着您可能需要预先假定类型,或者如果结构可能有所不同,则需要某种type switch


0
投票

您无法使用result[][]访问内部属性。您需要执行以下操作,

info:= result["info"]
v := info.(map[string]interface{})
json_data = v["Date"]
© www.soinside.com 2019 - 2024. All rights reserved.