forked from tdewolff/minify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
63 lines (51 loc) · 1.51 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Package json minifies JSON following the specifications at http://json.org/.
package json // import "github.com/tdewolff/minify/json"
import (
"io"
"github.com/tdewolff/minify"
"github.com/tdewolff/parse/json"
)
var (
commaBytes = []byte(",")
colonBytes = []byte(":")
)
////////////////////////////////////////////////////////////////
// DefaultMinifier is the default minifier.
var DefaultMinifier = &Minifier{}
// Minifier is a JSON minifier.
type Minifier struct{}
// Minify minifies JSON data, it reads from r and writes to w.
func Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
return DefaultMinifier.Minify(m, w, r, params)
}
// Minify minifies JSON data, it reads from r and writes to w.
func (o *Minifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
skipComma := true
p := json.NewParser(r)
defer p.Restore()
for {
state := p.State()
gt, text := p.Next()
if gt == json.ErrorGrammar {
if p.Err() != io.EOF {
return p.Err()
}
return nil
}
if !skipComma && gt != json.EndObjectGrammar && gt != json.EndArrayGrammar {
if state == json.ObjectKeyState || state == json.ArrayState {
if _, err := w.Write(commaBytes); err != nil {
return err
}
} else if state == json.ObjectValueState {
if _, err := w.Write(colonBytes); err != nil {
return err
}
}
}
skipComma = gt == json.StartObjectGrammar || gt == json.StartArrayGrammar
if _, err := w.Write(text); err != nil {
return err
}
}
}