Handling JSON in Go
What we want to do
- Read a JSON file and store it in a struct
- Handle escaping when writing a JSON file
- Output a JSON file
Reading a JSON file
- hoge.json
1 | { |
- main.go
1 | func main () { |
For why I use ioutil.ReadFile(filepath.Clean(fpath)) instead of ioutil.ReadFile(fpath), please refer to the following.
It read the file successfully!
But I want to use the id inside results[]… Even if you think so, you can’t get the value of id as it is.
1 | { |
Storing it in a struct
If you paste the JSON into JSON-to-Go, it generates a struct in no time.
1 | // Hoge : - |
json.Unmarshal(b, &hoge) stores the JSON data into hoge.
When you run it, you can see it gets the value properly.
1 | 2020/05/10 23:48:01 Title: "Hello, Gopher" |
Outputting a JSON file
Let’s write data of type map[int]int out to hoge.json.
1 | func main() { |
You can confirm that hoge.json is output.
1 | { |
Side note
I often see implementations that don’t check the error of json.Unmarshal.
It may be fine if, in your implementation, there’s no problem even when it fails, but in general you shouldn’t omit it.
1 | var hoge Hoge |
Besides that, there are cases where you’re actually not checking a function that returns an error type, so I deal with it using the following module.
1 | go get -u github.com/kisielk/errcheck |
In my Go projects, I always make sure to run it both in GitHub Actions and locally.
That’s all.
I hope this is helpful.
