Ian's blog
May 23 2022

Parse JSON with comments in Go

The Go standard library can’t parse json files containing comments or trailing commas. Doing so gives you the following error.

invalid character '/' looking for beginning of object key string

To prevent this error, you need to sanitize the json using the hujson package from Tailscale.

Here’s an example on how to use it, also available in the Go playground.

 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6
 7	"github.com/tailscale/hujson"
 8)
 9
10const data = `{
11  // Comment
12  "foo": "bar",
13}`
14
15type x struct {
16	Foo string `json:"foo"`
17}
18
19func main() {
20	var t x
21	data, err := standardizeJSON([]byte(data))
22	err = json.Unmarshal(data, &t)
23	if err != nil {
24		fmt.Println(err)
25		return
26	}
27
28	fmt.Println(t.Foo)
29}
30
31func standardizeJSON(b []byte) ([]byte, error) {
32	ast, err := hujson.Parse(b)
33	if err != nil {
34		return b, err
35	}
36	ast.Standardize()
37	return ast.Pack(), nil
38}