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
|
// Copyright (c) 2021, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package json
import (
"bytes"
ejson "encoding/json"
"fmt"
"math"
"sort"
"strconv"
"unicode/utf8"
)
type marshaler struct {
buf *bytes.Buffer
indent int
tmp []byte
}
// Marshal returns the JSON encoding of v. It differs from
// [encoding/json.Marshal] as it only handles map[string]any,
// []any, bool, float64, string, nil and
// [encoding/json.Marshaler] values. It also accepts "invalid" JSON data
// returned by MarshalJSON method.
func Marshal(v any, indent int) ([]byte, error) {
m := marshaler{
indent: indent,
buf: &bytes.Buffer{},
}
err := m.marshal(v)
if err != nil {
return nil, err
}
return m.buf.Bytes(), nil
}
// AppendMarshal does the same as [Marshal] but appends the JSON
// encoding to buf.
func AppendMarshal(buf *bytes.Buffer, v any, indent int) error {
m := marshaler{
indent: indent,
buf: buf,
}
return m.marshal(v)
}
func (m *marshaler) marshal(v any) error {
if v == nil {
m.buf.WriteString("null")
return nil
}
switch vt := v.(type) {
case map[string]any:
if len(vt) == 0 {
if vt == nil {
m.buf.WriteString("null")
} else {
m.buf.WriteString("{}")
}
break
}
m.indent += 2
keys := make([]string, 0, len(vt))
for k := range vt {
keys = append(keys, k)
}
sort.Strings(keys)
beg := "{\n"
for _, k := range keys {
m.buf.WriteString(beg)
beg = ",\n"
saveIndent, lenBefore := m.indent, m.buf.Len()
fmt.Fprintf(m.buf, `%*s%q: `, m.indent, "", k)
m.indent = utf8.RuneCount(m.buf.Bytes()[lenBefore:])
if err := m.marshal(vt[k]); err != nil {
return err
}
m.indent = saveIndent
}
m.indent -= 2
fmt.Fprintf(m.buf, "\n%*s}", m.indent, "")
case []any:
if len(vt) == 0 {
if vt == nil {
m.buf.WriteString("null")
} else {
m.buf.WriteString("[]")
}
break
}
m.indent += 2
beg := "[\n"
for _, v := range vt {
m.buf.WriteString(beg)
beg = ",\n"
fmt.Fprintf(m.buf, "%*s", m.indent, "")
if err := m.marshal(v); err != nil {
return err
}
}
m.indent -= 2
fmt.Fprintf(m.buf, "\n%*s]", m.indent, "")
case string:
fmt.Fprintf(m.buf, `%q`, vt)
case float64:
m.marshalFloat64(vt)
case bool:
if vt {
m.buf.WriteString("true")
} else {
m.buf.WriteString("false")
}
case ejson.Marshaler:
b, err := vt.MarshalJSON()
if err != nil {
return err
}
repl := bytes.Repeat([]byte(" "), 1+m.indent)
repl[0] = '\n'
m.buf.Write(bytes.ReplaceAll(b, []byte("\n"), repl))
default:
return fmt.Errorf("Cannot marshal %T", vt)
}
return nil
}
func (m *marshaler) marshalFloat64(f float64) {
// Contrary to JSON standard we accept to marshal NaN and ±Inf
if math.IsInf(f, 0) || math.IsNaN(f) {
m.tmp = strconv.AppendFloat(m.tmp[:0], f, 'g', -1, 64)
m.buf.Write(m.tmp)
return
}
// Remainder based on encoding/json.floatEncoder.encode()
// Convert as if by ES6 number to string conversion.
// This matches most other JSON generators.
// See golang.org/issue/6384 and golang.org/issue/14135.
// Like fmt %g, but the exponent cutoffs are different
// and exponents themselves are not padded to two digits.
abs := math.Abs(f)
fmt := byte('f')
if abs != 0 {
if abs < 1e-6 || abs >= 1e21 {
fmt = 'e'
}
}
m.tmp = strconv.AppendFloat(m.tmp[:0], f, fmt, -1, 64)
if fmt == 'e' {
// clean up e-09 to e-9
n := len(m.tmp)
if n >= 4 && m.tmp[n-4] == 'e' && m.tmp[n-3] == '-' && m.tmp[n-2] == '0' {
m.tmp[n-2] = m.tmp[n-1]
m.tmp = m.tmp[:n-1]
}
}
m.buf.Write(m.tmp)
}
|