| 1 | # canonicaljson-go |
| 2 | Go library for producing JSON in canonical format as specified by [https://gibson042.github.io/canonicaljson-spec/](https://gibson042.github.io/canonicaljson-spec/). |
| 3 | The provided interface matches that of standard package "[encoding/json](https://golang.org/pkg/encoding/json/)" wherever they overlap: |
| 4 | * [func `Marshal`](https://golang.org/pkg/encoding/json/#Marshal) |
| 5 | * [func `MarshalIndent`](https://golang.org/pkg/encoding/json/#MarshalIndent) |
| 6 | * [type `Encoder`](https://golang.org/pkg/encoding/json/#Encoder) |
| 7 | |
| 8 | Types from the standard package are also accepted wherever relevant. |
| 9 | |
| 10 | Test this package by invoking `test.sh`. |
| 11 | |
| 12 | ``` |
| 13 | godoc github.com/gibson042/canonicaljson-go |
| 14 | |
| 15 | PACKAGE DOCUMENTATION |
| 16 | |
| 17 | package canonicaljson |
| 18 | import "github.com/gibson042/canonicaljson-go" |
| 19 | |
| 20 | Package canonicaljson implements canonical serialization of Go objects |
| 21 | to canonical-form JSON as specified at |
| 22 | https://gibson042.github.io/canonicaljson-spec/ . The provided interface |
| 23 | should match that of standard package "encoding/json" (from which it is |
| 24 | derived) wherever they overlap (and in fact, this package is essentially |
| 25 | a 2016-03-09 fork from |
| 26 | golang/go@9d77ad8d34ce56e182adc30cd21af50a4b00932c:src/encoding/json ). |
| 27 | Notable differences: |
| 28 | |
| 29 | - Object keys are sorted lexicographically by code point |
| 30 | - Non-integer JSON numbers are represented in capital-E exponential |
| 31 | notation with significand in (-10, 10) and no insignificant signs |
| 32 | or zeroes beyond those required to force a decimal point. |
| 33 | - JSON strings are represented in UTF-8 with minimal byte length, |
| 34 | using escapes only when necessary for validity and Unicode |
| 35 | escapes (uppercase hex) only when there is no shorter option. |
| 36 | |
| 37 | FUNCTIONS |
| 38 | |
| 39 | func Marshal(v interface{}) ([]byte, error) |
| 40 | Marshal returns the canonical UTF-8 JSON encoding of v. |
| 41 | |
| 42 | Marshal traverses the value v recursively. If an encountered value |
| 43 | implements the json.Marshaler interface and is not a nil pointer, |
| 44 | Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON |
| 45 | method is present but the value implements encoding.TextMarshaler |
| 46 | instead, Marshal calls its MarshalText method. The nil pointer exception |
| 47 | is not strictly necessary but mimics a similar, necessary exception in |
| 48 | the behavior of json.UnmarshalJSON. |
| 49 | |
| 50 | Otherwise, Marshal uses the following type-dependent default encodings: |
| 51 | |
| 52 | Boolean values encode as JSON booleans. |
| 53 | |
| 54 | Floating point, integer, and Number values encode as JSON numbers. |
| 55 | Non-fractional values become sequences of digits without leading spaces; |
| 56 | fractional values are represented in capital-E exponential notation with |
| 57 | the shortest possible significand of magnitude less than 10 that |
| 58 | includes at least one digit both before and after the decimal point, and |
| 59 | the shortest possible non-empty exponent. |
| 60 | |
| 61 | String values encode as JSON strings, treating ill-formed UTF-8 input as |
| 62 | an error (with the exception of "WTF-8" encodings of lone |
| 63 | surrogates—code points U+D800 through U+DFFF [inclusive] that could not |
| 64 | be interpreted as part of a surrogate pair). This is in contrast to |
| 65 | encoding/json, which replaces ill-formed sequences with U+FFFD |
| 66 | REPLACEMENT CHARACTER. Also in contrast to encoding/json, characters |
| 67 | appear unescaped whenever possible. Control characters U+0000 through |
| 68 | U+001F and lone surrogates U+D800 through U+DFFF are replaced with their |
| 69 | shortest escape sequence, 4 uppercase hex characters except for the |
| 70 | following: |
| 71 | |
| 72 | - \b U+0008 BACKSPACE |
| 73 | - \t U+0009 CHARACTER TABULATION ("tab") |
| 74 | - \n U+000A LINE FEED ("newline") |
| 75 | - \f U+000C FORM FEED |
| 76 | - \r U+000D CARRIAGE RETURN |
| 77 | |
| 78 | Array and slice values encode as JSON arrays, except that []byte encodes |
| 79 | as a base64-encoded string, and a nil slice encodes as the null JSON |
| 80 | object. |
| 81 | |
| 82 | Struct values encode as JSON objects. Each exported struct field becomes |
| 83 | a member of the object unless |
| 84 | |
| 85 | - the field's tag is "-", or |
| 86 | - the field is empty and its tag specifies the "omitempty" option. |
| 87 | |
| 88 | The empty values are false, 0, any nil pointer or interface value, and |
| 89 | any array, slice, map, or string of length zero. The object's default |
| 90 | key string is the struct field name but can be specified in the struct |
| 91 | field's tag value. The "json" key in the struct field's tag value is the |
| 92 | key name, followed by an optional comma and options. Examples: |
| 93 | |
| 94 | // Field is ignored by this package. |
| 95 | Field int `json:"-"` |
| 96 | |
| 97 | // Field appears in JSON as key "myName". |
| 98 | Field int `json:"myName"` |
| 99 | |
| 100 | // Field appears in JSON as key "myName" and |
| 101 | // the field is omitted from the object if its value is empty, |
| 102 | // as defined above. |
| 103 | Field int `json:"myName,omitempty"` |
| 104 | |
| 105 | // Field appears in JSON as key "Field" (the default), but |
| 106 | // the field is skipped if empty. |
| 107 | // Note the leading comma. |
| 108 | Field int `json:",omitempty"` |
| 109 | |
| 110 | The "string" option signals that a field is stored as JSON inside a |
| 111 | JSON-encoded string. It applies only to fields of string, floating |
| 112 | point, integer, or boolean types. This extra level of encoding is |
| 113 | sometimes used when communicating with JavaScript programs: |
| 114 | |
| 115 | Int64String int64 `json:",string"` |
| 116 | |
| 117 | The key name will be used if it's a non-empty string consisting of only |
| 118 | Unicode letters, digits, dollar signs, percent signs, hyphens, |
| 119 | underscores and slashes. |
| 120 | |
| 121 | Anonymous struct fields are usually marshaled as if their inner exported |
| 122 | fields were fields in the outer struct, subject to the usual Go |
| 123 | visibility rules amended as described in the next paragraph. An |
| 124 | anonymous struct field with a name given in its JSON tag is treated as |
| 125 | having that name, rather than being anonymous. An anonymous struct field |
| 126 | of interface type is treated the same as having that type as its name, |
| 127 | rather than being anonymous. |
| 128 | |
| 129 | The Go visibility rules for struct fields are amended for JSON when |
| 130 | deciding which field to marshal. If there are multiple fields at the |
| 131 | same level, and that level is the least nested (and would therefore be |
| 132 | the nesting level selected by the usual Go rules), the following extra |
| 133 | rules apply: |
| 134 | |
| 135 | 1) Of those fields, if any are JSON-tagged, only tagged fields are |
| 136 | considered, even if there are multiple untagged fields that would |
| 137 | otherwise conflict. 2) If there is exactly one field (tagged or not |
| 138 | according to the first rule), that is selected. 3) Otherwise there are |
| 139 | multiple fields, and all are ignored; no error occurs. |
| 140 | |
| 141 | Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, |
| 142 | anonymous struct fields were ignored. To force ignoring of an anonymous |
| 143 | struct field in both current and earlier versions, give the field a JSON |
| 144 | tag of "-". |
| 145 | |
| 146 | Map values encode as JSON objects. The map's key type must be string; |
| 147 | the map keys are used as JSON object keys, subject to the UTF-8 coercion |
| 148 | described for string values above. |
| 149 | |
| 150 | Pointer values encode as the value pointed to. A nil pointer encodes as |
| 151 | the null JSON object. |
| 152 | |
| 153 | Interface values encode as the value contained in the interface. A nil |
| 154 | interface value encodes as the null JSON object. |
| 155 | |
| 156 | Channel, complex, and function values cannot be encoded in JSON. |
| 157 | Attempting to encode such a value causes Marshal to return an |
| 158 | UnsupportedTypeError. |
| 159 | |
| 160 | JSON cannot represent cyclic data structures and Marshal does not handle |
| 161 | them. Passing cyclic structures to Marshal will result in an infinite |
| 162 | recursion. |
| 163 | |
| 164 | func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) |
| 165 | MarshalIndent is like Marshal, but adds whitespace for more readable |
| 166 | output. |
| 167 | |
| 168 | func Unmarshal(data []byte, v interface{}) error |
| 169 | Unmarshal parses the JSON-encoded UTF-8 data and stores the result in |
| 170 | the value pointed to by v. |
| 171 | |
| 172 | Unmarshal uses the inverse of the encodings that Marshal uses, |
| 173 | allocating maps, slices, and pointers as necessary, with the following |
| 174 | additional rules: |
| 175 | |
| 176 | To unmarshal JSON into a pointer, Unmarshal first handles the case of |
| 177 | the JSON being the JSON literal null. In that case, Unmarshal sets the |
| 178 | pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value |
| 179 | pointed at by the pointer. If the pointer is nil, Unmarshal allocates a |
| 180 | new value for it to point to. |
| 181 | |
| 182 | To unmarshal JSON into a struct, Unmarshal matches incoming object keys |
| 183 | to the keys used by Marshal (either the struct field name or its tag), |
| 184 | preferring an exact match but also accepting a case-insensitive match. |
| 185 | Unmarshal will only set exported fields of the struct. |
| 186 | |
| 187 | To unmarshal JSON into an interface value, Unmarshal stores one of these |
| 188 | in the interface value: |
| 189 | |
| 190 | bool, for JSON booleans |
| 191 | float64, for JSON numbers |
| 192 | string, for JSON strings |
| 193 | []interface{}, for JSON arrays |
| 194 | map[string]interface{}, for JSON objects |
| 195 | nil for JSON null |
| 196 | |
| 197 | To unmarshal a JSON array into a slice, Unmarshal resets the slice |
| 198 | length to zero and then appends each element to the slice. As a special |
| 199 | case, to unmarshal an empty JSON array into a slice, Unmarshal replaces |
| 200 | the slice with a new empty slice. |
| 201 | |
| 202 | To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array |
| 203 | elements into corresponding Go array elements. If the Go array is |
| 204 | smaller than the JSON array, the additional JSON array elements are |
| 205 | discarded. If the JSON array is smaller than the Go array, the |
| 206 | additional Go array elements are set to zero values. |
| 207 | |
| 208 | To unmarshal a JSON object into a string-keyed map, Unmarshal first |
| 209 | establishes a map to use, If the map is nil, Unmarshal allocates a new |
| 210 | map. Otherwise Unmarshal reuses the existing map, keeping existing |
| 211 | entries. Unmarshal then stores key-value pairs from the JSON object into |
| 212 | the map. |
| 213 | |
| 214 | If a JSON value is not appropriate for a given target type, or if a JSON |
| 215 | number overflows the target type, Unmarshal skips that field and |
| 216 | completes the unmarshaling as best it can. If no more serious errors are |
| 217 | encountered, Unmarshal returns an UnmarshalTypeError describing the |
| 218 | earliest such error. |
| 219 | |
| 220 | The JSON null value unmarshals into an interface, map, pointer, or slice |
| 221 | by setting that Go value to nil. Because null is often used in JSON to |
| 222 | mean ``not present,'' unmarshaling a JSON null into any other Go type |
| 223 | has no effect on the value and produces no error. |
| 224 | |
| 225 | Invalid UTF-8 input is always treated as an error, even if it is |
| 226 | encountered when unmarshaling a quoted string (in contrast to |
| 227 | encoding/json, which replaces bad octets with U+FFFD REPLACEMENT |
| 228 | CHARACTER). However, `\uXXXX` JSON string escape sequences specifying |
| 229 | lone surrogates (code points U+D800 through U+DFFF [inclusive] that are |
| 230 | not part of a surrogate pair) are interpreted to produce "WTF-8" runes |
| 231 | that cannot be losslessly serialized to UTF-8 and might produce |
| 232 | unexpected behavior if passed to functions expecting all strings to |
| 233 | contain valid UTF-8. This package's Marshal function checks for such |
| 234 | runes and emits them as valid JSON escape sequences. |
| 235 | |
| 236 | TYPES |
| 237 | |
| 238 | type Decoder struct { |
| 239 | // contains filtered or unexported fields |
| 240 | } |
| 241 | A Decoder reads and decodes JSON objects from an input stream. |
| 242 | |
| 243 | func NewDecoder(r io.Reader) *Decoder |
| 244 | NewDecoder returns a new decoder that reads from r. |
| 245 | |
| 246 | The decoder introduces its own buffering and may read data from r beyond |
| 247 | the JSON values requested. |
| 248 | |
| 249 | func (dec *Decoder) Buffered() io.Reader |
| 250 | Buffered returns a reader of the data remaining in the Decoder's buffer. |
| 251 | The reader is valid until the next call to Decode. |
| 252 | |
| 253 | func (dec *Decoder) Decode(v interface{}) error |
| 254 | Decode reads the next JSON-encoded value from its input and stores it in |
| 255 | the value pointed to by v. |
| 256 | |
| 257 | See the documentation for Unmarshal for details about the conversion of |
| 258 | JSON into a Go value. |
| 259 | |
| 260 | func (dec *Decoder) More() bool |
| 261 | More reports whether there is another element in the current array or |
| 262 | object being parsed. |
| 263 | |
| 264 | func (dec *Decoder) Token() (Token, error) |
| 265 | Token returns the next JSON token in the input stream. At the end of the |
| 266 | input stream, Token returns nil, io.EOF. |
| 267 | |
| 268 | Token guarantees that the delimiters [ ] { } it returns are properly |
| 269 | nested and matched: if Token encounters an unexpected delimiter in the |
| 270 | input, it will return an error. |
| 271 | |
| 272 | The input stream consists of basic JSON values—bool, string, number, and |
| 273 | null—along with delimiters [ ] { } of type Delim to mark the start and |
| 274 | end of arrays and objects. Commas and colons are elided. |
| 275 | |
| 276 | func (dec *Decoder) UseNumber() |
| 277 | UseNumber causes the Decoder to unmarshal a number into an interface{} |
| 278 | as a Number instead of as a float64. |
| 279 | |
| 280 | type Delim rune |
| 281 | A Delim is a JSON array or object delimiter, one of [ ] { or }. |
| 282 | |
| 283 | func (d Delim) String() string |
| 284 | |
| 285 | type Encoder struct { |
| 286 | // contains filtered or unexported fields |
| 287 | } |
| 288 | An Encoder writes JSON objects to an output stream. |
| 289 | |
| 290 | func NewEncoder(w io.Writer) *Encoder |
| 291 | NewEncoder returns a new encoder that writes to w. |
| 292 | |
| 293 | func (enc *Encoder) Encode(v interface{}) error |
| 294 | Encode writes the JSON encoding of v to the stream, followed by a |
| 295 | newline character. |
| 296 | |
| 297 | See the documentation for Marshal for details about the conversion of Go |
| 298 | values to JSON. |
| 299 | |
| 300 | type InvalidUnmarshalError struct { |
| 301 | Type reflect.Type |
| 302 | } |
| 303 | An InvalidUnmarshalError describes an invalid argument passed to |
| 304 | Unmarshal. (The argument to Unmarshal must be a non-nil pointer.) |
| 305 | |
| 306 | func (e *InvalidUnmarshalError) Error() string |
| 307 | |
| 308 | type Marshaler interface { |
| 309 | MarshalJSON() ([]byte, error) |
| 310 | } |
| 311 | Marshaler is the interface implemented by objects that can marshal |
| 312 | themselves into valid JSON. |
| 313 | |
| 314 | type MarshalerError struct { |
| 315 | Type reflect.Type |
| 316 | Err error |
| 317 | } |
| 318 | |
| 319 | func (e *MarshalerError) Error() string |
| 320 | |
| 321 | type Number string |
| 322 | A Number represents a JSON number literal. TODO(go>=1.9): type Number = |
| 323 | json.Number |
| 324 | |
| 325 | func (n Number) Float64() (float64, error) |
| 326 | Float64 returns the number as a float64. |
| 327 | |
| 328 | func (n Number) Int64() (int64, error) |
| 329 | Int64 returns the number as an int64. |
| 330 | |
| 331 | func (n Number) String() string |
| 332 | String returns the literal text of the number. |
| 333 | |
| 334 | type RawMessage []byte |
| 335 | RawMessage is a raw encoded JSON object. It implements Marshaler and |
| 336 | Unmarshaler and can be used to delay JSON decoding or precompute a JSON |
| 337 | encoding. |
| 338 | |
| 339 | func (m *RawMessage) MarshalJSON() ([]byte, error) |
| 340 | MarshalJSON returns *m as the JSON encoding of m. |
| 341 | |
| 342 | func (m *RawMessage) UnmarshalJSON(data []byte) error |
| 343 | UnmarshalJSON sets *m to a copy of data. |
| 344 | |
| 345 | type SyntaxError struct { |
| 346 | Offset int64 // error occurred after reading Offset bytes |
| 347 | // contains filtered or unexported fields |
| 348 | } |
| 349 | A SyntaxError is a description of a JSON syntax error. |
| 350 | |
| 351 | func (e *SyntaxError) Error() string |
| 352 | |
| 353 | type Token interface{} |
| 354 | A Token holds a value of one of these types: |
| 355 | |
| 356 | Delim, for the four JSON delimiters [ ] { } |
| 357 | bool, for JSON booleans |
| 358 | float64, for JSON numbers |
| 359 | Number, for JSON numbers |
| 360 | string, for JSON string literals |
| 361 | nil, for JSON null |
| 362 | |
| 363 | type UnmarshalFieldError struct { |
| 364 | Key string |
| 365 | Type reflect.Type |
| 366 | Field reflect.StructField |
| 367 | } |
| 368 | An UnmarshalFieldError describes a JSON object key that led to an |
| 369 | unexported (and therefore unwritable) struct field. (No longer used; |
| 370 | kept for compatibility.) |
| 371 | |
| 372 | func (e *UnmarshalFieldError) Error() string |
| 373 | |
| 374 | type UnmarshalTypeError struct { |
| 375 | Value string // description of JSON value - "bool", "array", "number -5" |
| 376 | Type reflect.Type // type of Go value it could not be assigned to |
| 377 | Offset int64 // error occurred after reading Offset bytes |
| 378 | } |
| 379 | An UnmarshalTypeError describes a JSON value that was not appropriate |
| 380 | for a value of a specific Go type. |
| 381 | |
| 382 | func (e *UnmarshalTypeError) Error() string |
| 383 | |
| 384 | type Unmarshaler interface { |
| 385 | UnmarshalJSON([]byte) error |
| 386 | } |
| 387 | Unmarshaler is the interface implemented by objects that can unmarshal a |
| 388 | JSON description of themselves. The input can be assumed to be a valid |
| 389 | encoding of a JSON value. UnmarshalJSON must copy the JSON data if it |
| 390 | wishes to retain the data after returning. |
| 391 | |
| 392 | type UnsupportedTypeError struct { |
| 393 | Type reflect.Type |
| 394 | } |
| 395 | An UnsupportedTypeError is returned by Marshal when attempting to encode |
| 396 | an unsupported value type. |
| 397 | |
| 398 | func (e *UnsupportedTypeError) Error() string |
| 399 | |
| 400 | type UnsupportedValueError struct { |
| 401 | Value reflect.Value |
| 402 | Str string |
| 403 | } |
| 404 | |
| 405 | func (e *UnsupportedValueError) Error() string |
| 406 | |
| 407 | SUBDIRECTORIES |
| 408 | |
| 409 | canonicaljson-spec |
| 410 | cli |
| 411 | ``` |