简体   繁体   中英

Parse JSON correctly in Go

From last 2 days I'm somehow stuck with JSON and Go. My aim is very simple, one Go program that can read a JSON file, output it correctly and append some items to that JSON and then rewrite it back to disk.

Saved JSON File.

{
"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"]
    }
  }
}

I have successfully parsed the JSON in Go but then when I try to get JSON["Info"]["Date"] it throws interface error. I can't make a specific struct because all the items will dynamically change whenever the code/API gets called.

The Code that I'm using to parse the data

// 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

Any help/lead is highly appreciated. Thanks a-lot in advance.

Unfortunately, you have to assert types every time you access the parsed data:

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

Now date is map[string]interface{} , but its statically known type is still interface{} .

That means you either need to assume the type in advance or have some kind of a type switch if the structure may vary.

you can't access inner properties with result[][] . You need to do something like follows,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM