forked from basgys/goxml2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
220 lines (195 loc) · 4.57 KB
/
encoder.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package xml2json
import (
"bytes"
"io"
"unicode/utf8"
"github.com/pkg/errors"
)
// An Encoder writes JSON objects to an output stream.
type Encoder struct {
writer io.Writer
err error
contentPrefix string
attributePrefix string
tc encoderTypeConverter
allAttributeToArray bool
attrIsAlwaysAnArray map[string]bool
}
// NewEncoder returns a new encoder that writes to writer.
func NewEncoder(writer io.Writer, plugins ...Plugin) *Encoder {
e := &Encoder{
writer: writer,
contentPrefix: "",
attributePrefix: "",
}
for _, p := range plugins {
e = p.AddToEncoder(e)
}
return e
}
// Encode writes the JSON encoding of v to the stream
func (enc *Encoder) Encode(root *Node) error {
if enc.err != nil {
return enc.err
}
if root == nil {
return nil
}
enc.err = enc.format(root, 0)
// Terminate each value with a newline.
// This makes the output look a little nicer
// when debugging, and some kind of space
// is required if the encoded value was a number,
// so that the reader knows there aren't more
// digits coming.
enc.write("\n")
return enc.err
}
func (enc *Encoder) format(n *Node, lvl int) error {
if n.IsComplex() {
enc.write("{")
// Add data as an additional attibute (if any)
if len(n.Data) > 0 {
enc.write("\"")
enc.write(enc.contentPrefix)
enc.write("content")
if enc.allAttributeToArray {
enc.write("\": [")
enc.write(sanitiseString(n.Data))
enc.write("], ")
} else {
enc.write("\": ")
enc.write(sanitiseString(n.Data))
enc.write(", ")
}
}
i := 0
tot := len(n.Children)
for label, children := range n.Children {
enc.write("\"")
enc.write(label)
enc.write("\": ")
if enc.allAttributeToArray || len(children) > 1 {
// Array
enc.write("[")
for j, c := range children {
err := enc.format(c, lvl+1)
if err != nil {
return errors.WithMessagef(err, "format %s children", label)
}
if j < len(children)-1 {
enc.write(", ")
}
}
enc.write("]")
} else {
child := children[0]
attrIsArray := enc.attrIsAlwaysAnArray[child.Label]
if attrIsArray {
enc.write("[")
}
// Map
err := enc.format(child, lvl+1)
if err != nil {
return errors.WithMessagef(err, "format %s children", label)
}
if attrIsArray {
enc.write("]")
}
}
if i < tot-1 {
enc.write(", ")
}
i++
}
enc.write("}")
} else {
s := sanitiseString(n.Data)
if enc.tc == nil {
// do nothing
} else {
s = enc.tc.Convert(s)
}
enc.write(s)
}
return nil
}
func (enc *Encoder) write(s string) {
enc.writer.Write([]byte(s))
}
// https://golang.org/src/encoding/json/encode.go?s=5584:5627#L788
var hex = "0123456789abcdef"
func sanitiseString(s string) string {
var buf bytes.Buffer
buf.WriteByte('"')
start := 0
for i := 0; i < len(s); {
if b := s[i]; b < utf8.RuneSelf {
if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
i++
continue
}
if start < i {
buf.WriteString(s[start:i])
}
switch b {
case '\\', '"':
buf.WriteByte('\\')
buf.WriteByte(b)
case '\n':
buf.WriteByte('\\')
buf.WriteByte('n')
case '\r':
buf.WriteByte('\\')
buf.WriteByte('r')
case '\t':
buf.WriteByte('\\')
buf.WriteByte('t')
default:
// This encodes bytes < 0x20 except for \n and \r,
// as well as <, > and &. The latter are escaped because they
// can lead to security holes when user-controlled strings
// are rendered into JSON and served to some browsers.
buf.WriteString(`\u00`)
buf.WriteByte(hex[b>>4])
buf.WriteByte(hex[b&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 {
if start < i {
buf.WriteString(s[start:i])
}
buf.WriteString(`\ufffd`)
i += size
start = i
continue
}
// U+2028 is LINE SEPARATOR.
// U+2029 is PARAGRAPH SEPARATOR.
// They are both technically valid characters in JSON strings,
// but don't work in JSONP, which has to be evaluated as JavaScript,
// and can lead to security holes there. It is valid JSON to
// escape them, so we do so unconditionally.
// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
if c == '\u2028' || c == '\u2029' {
if start < i {
buf.WriteString(s[start:i])
}
buf.WriteString(`\u202`)
buf.WriteByte(hex[c&0xF])
i += size
start = i
continue
}
i += size
}
if start < len(s) {
buf.WriteString(s[start:])
}
buf.WriteByte('"')
return buf.String()
}