-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathjson.go
92 lines (88 loc) · 2.04 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
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
package main
import (
"bytes"
"howl.moe/nanojson"
)
func attemptJSONFormatting(msg []byte) []byte {
virtualV := nanojson.Pools.Value.Get()
v := virtualV.(*nanojson.Value)
err := v.Parse(msg)
if err != nil {
return msg
}
buf := new(bytes.Buffer)
printValue(buf, v, "")
return buf.Bytes()
}
func printValue(buf *bytes.Buffer, v *nanojson.Value, indent string) {
indent += " "
switch v.Kind {
case nanojson.KindString:
v.EncodeJSON(buf)
case nanojson.KindNumber:
buf.Write(v.Value)
case nanojson.KindObject:
if len(v.Children) == 0 {
buf.WriteString("{}")
return
}
// get tmpV which we will use to encode keys as JSON strings
virtualTmpV := nanojson.Pools.Value.Get()
tmpV := virtualTmpV.(*nanojson.Value)
tmpV.Kind = nanojson.KindString
if len(v.Children) == 1 {
buf.WriteByte('{')
// encode key
tmpV.Value = v.Children[0].Key
tmpV.EncodeJSON(buf)
buf.WriteString(": ")
// encode value
printValue(buf, &v.Children[0], indent)
buf.WriteByte('}')
return
}
buf.WriteString("{\n")
for i := 0; i < len(v.Children); i++ {
buf.WriteString(indent)
tmpV.Value = v.Children[i].Key
tmpV.EncodeJSON(buf)
buf.WriteString(": ")
printValue(buf, &v.Children[i], indent)
if i != len(v.Children)-1 {
buf.WriteByte(',')
}
buf.WriteByte('\n')
}
buf.WriteString(indent[:len(indent)-2])
buf.WriteByte('}')
case nanojson.KindArray:
switch len(v.Children) {
case 0:
buf.WriteString("[]")
case 1:
buf.WriteByte('[')
printValue(buf, &v.Children[0], indent)
buf.WriteByte(']')
default:
buf.WriteString("[\n")
for i := 0; i < len(v.Children); i++ {
buf.WriteString(indent)
printValue(buf, &v.Children[i], indent)
if i != len(v.Children)-1 {
buf.WriteByte(',')
}
buf.WriteByte('\n')
}
buf.WriteString(indent[:len(indent)-2])
buf.WriteByte(']')
}
case nanojson.KindTrue:
buf.WriteString("true")
case nanojson.KindFalse:
buf.WriteString("false")
case nanojson.KindNull:
buf.WriteString("null")
default:
buf.WriteString("(INVALID)")
}
}