Skip to content

Commit 1659de6

Browse files
committed
- [+] add final tested version
1 parent 3e3ff29 commit 1659de6

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Go JSON File Handling
2+
3+
This package provides simple wrapping around saving and reading JSON files (streams) in GO. It exists because way too many sample/demo code are doing it the wrong way. Wrong in the sense of efficiency -- when reading JSON from file for example, the right is to read from stream, instead of reading the whole file via `ioutil.ReadAll` into a big buffer first then decode the buffer next.
4+
5+
Every single hit I searched, for "JSON files reading writing", is doing reading like this. They are actually not wrong, but just not ideal, especially when it comes to big JSON files.
6+
7+
Hence, this simple JSON files reading writing wrapping package. Here is a [simple demo code](https://github.com/suntong/lang/blob/master/lang/Go/src/ds/jsonfile.go).
8+

jsonfile.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
////////////////////////////////////////////////////////////////////////////
2+
// Porgram: jsonfile.go
3+
// Purpose: GO JSON File Handling
4+
// Authors: Tong Sun (c) 2016, All rights reserved
5+
// Credits: Mkideal Wang https://github.com/mkideal/cli/issues/22
6+
////////////////////////////////////////////////////////////////////////////
7+
8+
package jsonfile
9+
10+
import (
11+
"encoding/json"
12+
"io"
13+
"os"
14+
)
15+
16+
// ReadJSON reads JSON from stream.
17+
func ReadJSON(r io.Reader, js interface{}) error {
18+
return json.NewDecoder(r).Decode(js)
19+
}
20+
21+
// ReadJSONFromFile reads JSON from the file with given name.
22+
func ReadJSONFromFile(filename string, js interface{}) error {
23+
file, err := os.Open(filename)
24+
defer file.Close()
25+
if err != nil {
26+
return err
27+
}
28+
return ReadJSON(file, js)
29+
}
30+
31+
// WriteJSON writes JSON to the stream.
32+
func WriteJSON(w io.Writer, js interface{}) error {
33+
return json.NewEncoder(w).Encode(js)
34+
}
35+
36+
// WriteJSONFromFile writes JSON to the file with given name.
37+
func WriteJSONToFile(filename string, js interface{}) error {
38+
file, err := os.Create(filename)
39+
defer file.Close()
40+
if err != nil {
41+
return err
42+
}
43+
return WriteJSON(file, js)
44+
}

0 commit comments

Comments
 (0)