YAML vs JSON vs XML in Go.
--
In a recent Go project, I had to choose what data format to use for sending and receiving data. My usual go-to is JSON, but I decided I would give an honest comparison of the options. As I’m sure you’ve gleaned from the title, the main contenders are YAML, JSON and XML. The criteria I have evaluated them on are:
- Human readability. It’s good to be able to read the data during development and debugging.
- Size. What size will the data be once it’s been encoded?
- Speed. How long does it take to parse and encode the formats?
To evaluate them I needed a decent amount of data, that’s fairly complex and is freely available (so I can write about it here without worrying). The data I have chosen is the Debian Vulnerability Data, available in JSON here. It’s freely available, has a few thousand entries and has multiple layers, so it’s perfect! (It’s updated daily, so might have changed since I took a copy). I modified it slightly to play better with the chosen formats (looking at you XML!). I then wrote a small Go program to load the data in, Unmarshal it using each format and then Marshal them using each format. The full code and data can be found on Github. A small sample looks like this:
func unmarshalThenMarshalYAML(dataBytes []byte) (int64, int64) { vulnData := DebianVulnData{} startUnmarshal := time.Now()
err := yaml.Unmarshal(dataBytes, &vulnData)
if err != nil {
log.Fatalf("error: %v", err)
}
unmarshalDuration := time.Since(startUnmarshal) startMarshal := time.Now()
yamlData, err := yaml.Marshal(&vulnData)
if err != nil {
log.Fatalf("error: %v", err)
}
marshalDuration := time.Since(startMarshal) log.Printf("YAML time unmarshal: %dms. marshal: %d\n", unmarshalDuration.Milliseconds(), marshalDuration.Milliseconds()) log.Panicln("YAML packages len ", len(vulnData.Packages))
log.Println("YAML output len ", len(yamlData)) return unmarshalDuration.Milliseconds(), marshalDuration.Milliseconds()
}
Now have our data and a way to compare the speed and size, let's get comparing!



