| 1 |
// Copyright (c) 2021, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package json |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
ejson "encoding/json" |
| 12 |
"fmt" |
| 13 |
"math" |
| 14 |
"sort" |
| 15 |
"strconv" |
| 16 |
"unicode/utf8" |
| 17 |
) |
| 18 |
|
| 19 |
type marshaler struct { |
| 20 |
buf *bytes.Buffer |
| 21 |
indent int |
| 22 |
tmp []byte |
| 23 |
} |
| 24 |
|
| 25 |
// Marshal returns the JSON encoding of v. It differs from |
| 26 |
// [encoding/json.Marshal] as it only handles map[string]any, |
| 27 |
// []any, bool, float64, string, nil and |
| 28 |
// [encoding/json.Marshaler] values. It also accepts "invalid" JSON data |
| 29 |
// returned by MarshalJSON method. |
| 30 |
func Marshal(v any, indent int) ([]byte, error) { |
| 31 |
m := marshaler{ |
| 32 |
indent: indent, |
| 33 |
buf: &bytes.Buffer{}, |
| 34 |
} |
| 35 |
err := m.marshal(v) |
| 36 |
if err != nil { |
| 37 |
return nil, err |
| 38 |
} |
| 39 |
return m.buf.Bytes(), nil |
| 40 |
} |
| 41 |
|
| 42 |
// AppendMarshal does the same as [Marshal] but appends the JSON |
| 43 |
// encoding to buf. |
| 44 |
func AppendMarshal(buf *bytes.Buffer, v any, indent int) error { |
| 45 |
m := marshaler{ |
| 46 |
indent: indent, |
| 47 |
buf: buf, |
| 48 |
} |
| 49 |
return m.marshal(v) |
| 50 |
} |
| 51 |
|
| 52 |
func (m *marshaler) marshal(v any) error { |
| 53 |
if v == nil { |
| 54 |
m.buf.WriteString("null") |
| 55 |
return nil |
| 56 |
} |
| 57 |
|
| 58 |
switch vt := v.(type) { |
| 59 |
case map[string]any: |
| 60 |
if len(vt) == 0 { |
| 61 |
if vt == nil { |
| 62 |
m.buf.WriteString("null") |
| 63 |
} else { |
| 64 |
m.buf.WriteString("{}") |
| 65 |
} |
| 66 |
break |
| 67 |
} |
| 68 |
m.indent += 2 |
| 69 |
keys := make([]string, 0, len(vt)) |
| 70 |
for k := range vt { |
| 71 |
keys = append(keys, k) |
| 72 |
} |
| 73 |
sort.Strings(keys) |
| 74 |
beg := "{\n" |
| 75 |
for _, k := range keys { |
| 76 |
m.buf.WriteString(beg) |
| 77 |
beg = ",\n" |
| 78 |
|
| 79 |
saveIndent, lenBefore := m.indent, m.buf.Len() |
| 80 |
fmt.Fprintf(m.buf, `%*s%q: `, m.indent, "", k) |
| 81 |
m.indent = utf8.RuneCount(m.buf.Bytes()[lenBefore:]) |
| 82 |
if err := m.marshal(vt[k]); err != nil { |
| 83 |
return err |
| 84 |
} |
| 85 |
m.indent = saveIndent |
| 86 |
} |
| 87 |
m.indent -= 2 |
| 88 |
fmt.Fprintf(m.buf, "\n%*s}", m.indent, "") |
| 89 |
|
| 90 |
case []any: |
| 91 |
if len(vt) == 0 { |
| 92 |
if vt == nil { |
| 93 |
m.buf.WriteString("null") |
| 94 |
} else { |
| 95 |
m.buf.WriteString("[]") |
| 96 |
} |
| 97 |
break |
| 98 |
} |
| 99 |
m.indent += 2 |
| 100 |
beg := "[\n" |
| 101 |
for _, v := range vt { |
| 102 |
m.buf.WriteString(beg) |
| 103 |
beg = ",\n" |
| 104 |
fmt.Fprintf(m.buf, "%*s", m.indent, "") |
| 105 |
if err := m.marshal(v); err != nil { |
| 106 |
return err |
| 107 |
} |
| 108 |
} |
| 109 |
m.indent -= 2 |
| 110 |
fmt.Fprintf(m.buf, "\n%*s]", m.indent, "") |
| 111 |
|
| 112 |
case string: |
| 113 |
fmt.Fprintf(m.buf, `%q`, vt) |
| 114 |
|
| 115 |
case float64: |
| 116 |
m.marshalFloat64(vt) |
| 117 |
|
| 118 |
case bool: |
| 119 |
if vt { |
| 120 |
m.buf.WriteString("true") |
| 121 |
} else { |
| 122 |
m.buf.WriteString("false") |
| 123 |
} |
| 124 |
|
| 125 |
case ejson.Marshaler: |
| 126 |
b, err := vt.MarshalJSON() |
| 127 |
if err != nil { |
| 128 |
return err |
| 129 |
} |
| 130 |
repl := bytes.Repeat([]byte(" "), 1+m.indent) |
| 131 |
repl[0] = '\n' |
| 132 |
m.buf.Write(bytes.ReplaceAll(b, []byte("\n"), repl)) |
| 133 |
|
| 134 |
default: |
| 135 |
return fmt.Errorf("cannot marshal %T", vt) |
| 136 |
} |
| 137 |
|
| 138 |
return nil |
| 139 |
} |
| 140 |
|
| 141 |
func (m *marshaler) marshalFloat64(f float64) { |
| 142 |
// Contrary to JSON standard we accept to marshal NaN and ±Inf |
| 143 |
if math.IsInf(f, 0) || math.IsNaN(f) { |
| 144 |
m.tmp = strconv.AppendFloat(m.tmp[:0], f, 'g', -1, 64) |
| 145 |
m.buf.Write(m.tmp) |
| 146 |
return |
| 147 |
} |
| 148 |
|
| 149 |
// Remainder based on encoding/json.floatEncoder.encode() |
| 150 |
|
| 151 |
// Convert as if by ES6 number to string conversion. |
| 152 |
// This matches most other JSON generators. |
| 153 |
// See golang.org/issue/6384 and golang.org/issue/14135. |
| 154 |
// Like fmt %g, but the exponent cutoffs are different |
| 155 |
// and exponents themselves are not padded to two digits. |
| 156 |
abs := math.Abs(f) |
| 157 |
fmt := byte('f') |
| 158 |
|
| 159 |
if abs != 0 { |
| 160 |
if abs < 1e-6 || abs >= 1e21 { |
| 161 |
fmt = 'e' |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
m.tmp = strconv.AppendFloat(m.tmp[:0], f, fmt, -1, 64) |
| 166 |
if fmt == 'e' { |
| 167 |
// clean up e-09 to e-9 |
| 168 |
n := len(m.tmp) |
| 169 |
if n >= 4 && m.tmp[n-4] == 'e' && m.tmp[n-3] == '-' && m.tmp[n-2] == '0' { |
| 170 |
m.tmp[n-2] = m.tmp[n-1] |
| 171 |
m.tmp = m.tmp[:n-1] |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
m.buf.Write(m.tmp) |
| 176 |
} |