CanonicalJSONNumbers returns v with every number replaced by one canonical spelling of its exact value, for code that COMPARES decoded field values (BUG-3202). Since field writes keep a number's literal, one value can be stored as different text (1e3, 1000, 1000.0); comparing that text reports a cha
(v any)
| 144 | // mutated. The result is for comparison and marshals to valid JSON, but it is |
| 145 | // NOT a storage form: it rewrites the caller's spelling. |
| 146 | func CanonicalJSONNumbers(v any) any { |
| 147 | switch x := v.(type) { |
| 148 | case map[string]any: |
| 149 | out := make(map[string]any, len(x)) |
| 150 | for k, e := range x { |
| 151 | out[k] = CanonicalJSONNumbers(e) |
| 152 | } |
| 153 | return out |
| 154 | case []any: |
| 155 | out := make([]any, len(x)) |
| 156 | for i, e := range x { |
| 157 | out[i] = CanonicalJSONNumbers(e) |
| 158 | } |
| 159 | return out |
| 160 | case json.Number: |
| 161 | return json.Number(canonicalNumberLiteral(string(x))) |
| 162 | case float64: |
| 163 | return json.Number(canonicalNumberLiteral(strconv.FormatFloat(x, 'g', -1, 64))) |
| 164 | } |
| 165 | return v |
| 166 | } |
| 167 | |
| 168 | // canonicalNumberLiteral rewrites a JSON number literal as |
| 169 | // [-]<digits without leading or trailing zeros>e<exponent>, which is exact |