| 1 |
# JSON Serialization (v2) |
| 2 |
|
| 3 |
[](https://pkg.go.dev/github.com/go-json-experiment/json) |
| 4 |
[](https://github.com/go-json-experiment/json/actions) |
| 5 |
|
| 6 |
This module hosts an experimental implementation of v2 `encoding/json`. |
| 7 |
The API is unstable and breaking changes will regularly be made. |
| 8 |
Do not depend on this in publicly available modules. |
| 9 |
|
| 10 |
Any commits that make breaking API or behavior changes will be marked |
| 11 |
with the string "WARNING: " near the top of the commit message. |
| 12 |
It is your responsibility to inspect the list of commit changes |
| 13 |
when upgrading the module. Not all breaking changes will lead to build failures. |
| 14 |
|
| 15 |
A [proposal to include this module in Go as `encoding/json/v2` and `encoding/json/jsontext`](https://github.com/golang/go/issues/71497) has been started on the Go Github project on 2025-01-30. Please provide your feedback there. |
| 16 |
|
| 17 |
## Goals and objectives |
| 18 |
|
| 19 |
* **Mostly backwards compatible:** If possible, v2 should aim to be _mostly_ |
| 20 |
compatible with v1 in terms of both API and default behavior to ease migration. |
| 21 |
For example, the `Marshal` and `Unmarshal` functions are the most widely used |
| 22 |
declarations in the v1 package. It seems sensible for equivalent functionality |
| 23 |
in v2 to be named the same and have a mostly compatible signature. |
| 24 |
Behaviorally, we should aim for 95% to 99% backwards compatibility. |
| 25 |
We do not aim for 100% compatibility since we want the freedom to break |
| 26 |
certain behaviors that are now considered to have been a mistake. |
| 27 |
Options exist that can bring the v2 implementation to 100% compatibility, |
| 28 |
but it will not be the default. |
| 29 |
|
| 30 |
* **More flexible:** There is a |
| 31 |
[long list of feature requests](https://github.com/golang/go/issues?q=is%3Aissue+is%3Aopen+encoding%2Fjson+in%3Atitle). |
| 32 |
We should aim to provide the most flexible features that addresses most usages. |
| 33 |
We do not want to over fit the v2 API to handle every possible use case. |
| 34 |
Ideally, the features provided should be orthogonal in nature such that |
| 35 |
any combination of features results in as few surprising edge cases as possible. |
| 36 |
|
| 37 |
* **More performant:** JSON serialization is widely used and any bit of extra |
| 38 |
performance gains will be greatly appreciated. Some rarely used behaviors of v1 |
| 39 |
may be dropped in favor of better performance. For example, |
| 40 |
despite `Encoder` and `Decoder` operating on an `io.Writer` and `io.Reader`, |
| 41 |
they do not operate in a truly streaming manner, |
| 42 |
leading to a loss in performance. The v2 implementation should aim to be truly |
| 43 |
streaming by default (see [#33714](https://golang.org/issue/33714)). |
| 44 |
|
| 45 |
* **Easy to use (hard to misuse):** The v2 API should aim to make |
| 46 |
the common case easy and the less common case at least possible. |
| 47 |
The API should avoid behavior that goes contrary to user expectation, |
| 48 |
which may result in subtle bugs (see [#36225](https://golang.org/issue/36225)). |
| 49 |
|
| 50 |
* **v1 and v2 maintainability:** Since the v1 implementation must stay forever, |
| 51 |
it would be beneficial if v1 could be implemented under the hood with v2, |
| 52 |
allowing for less maintenance burden in the future. This probably implies that |
| 53 |
behavioral changes in v2 relative to v1 need to be exposed as options. |
| 54 |
|
| 55 |
* **Avoid unsafe:** Standard library packages generally avoid the use of |
| 56 |
package `unsafe` even if it could provide a performance boost. |
| 57 |
We aim to preserve this property. |
| 58 |
|
| 59 |
## Expectations |
| 60 |
|
| 61 |
While this module aims to possibly be the v2 implementation of `encoding/json`, |
| 62 |
there is no guarantee that this outcome will occur. As with any major change |
| 63 |
to the Go standard library, this will eventually go through the |
| 64 |
[Go proposal process](https://github.com/golang/proposal#readme). |
| 65 |
At the present moment, this is still in the design and experimentation phase |
| 66 |
and is not ready for a formal proposal. |
| 67 |
|
| 68 |
There are several possible outcomes from this experiment: |
| 69 |
1. We determine that a v2 `encoding/json` would not provide sufficient benefit |
| 70 |
over the existing v1 `encoding/json` package. Thus, we abandon this effort. |
| 71 |
2. We propose a v2 `encoding/json` design, but it is rejected in favor of some |
| 72 |
other design that is considered superior. |
| 73 |
3. We propose a v2 `encoding/json` design, but rather than adding an entirely |
| 74 |
new v2 `encoding/json` package, we decide to merge its functionality into |
| 75 |
the existing v1 `encoding/json` package. |
| 76 |
4. We propose a v2 `encoding/json` design and it is accepted, resulting in |
| 77 |
its addition to the standard library. |
| 78 |
5. Some other unforeseen outcome (among the infinite number of possibilities). |
| 79 |
|
| 80 |
## Development |
| 81 |
|
| 82 |
This module is primarily developed by |
| 83 |
[@dsnet](https://github.com/dsnet), |
| 84 |
[@mvdan](https://github.com/mvdan), and |
| 85 |
[@johanbrandhorst](https://github.com/johanbrandhorst) |
| 86 |
with feedback provided by |
| 87 |
[@rogpeppe](https://github.com/rogpeppe), |
| 88 |
[@ChrisHines](https://github.com/ChrisHines), and |
| 89 |
[@rsc](https://github.com/rsc). |
| 90 |
|
| 91 |
Discussion about semantics occur semi-regularly, where a |
| 92 |
[record of past meetings can be found here](https://docs.google.com/document/d/1rovrOTd-wTawGMPPlPuKhwXaYBg9VszTXR9AQQL5LfI/edit?usp=sharing). |
| 93 |
|
| 94 |
## Design overview |
| 95 |
|
| 96 |
This package aims to provide a clean separation between syntax and semantics. |
| 97 |
Syntax deals with the structural representation of JSON (as specified in |
| 98 |
[RFC 4627](https://tools.ietf.org/html/rfc4627), |
| 99 |
[RFC 7159](https://tools.ietf.org/html/rfc7159), |
| 100 |
[RFC 7493](https://tools.ietf.org/html/rfc7493), |
| 101 |
[RFC 8259](https://tools.ietf.org/html/rfc8259), and |
| 102 |
[RFC 8785](https://tools.ietf.org/html/rfc8785)). |
| 103 |
Semantics deals with the meaning of syntactic data as usable application data. |
| 104 |
|
| 105 |
The `Encoder` and `Decoder` types are streaming tokenizers concerned with the |
| 106 |
packing or parsing of JSON data. They operate on `Token` and `Value` types |
| 107 |
which represent the common data structures that are representable in JSON. |
| 108 |
`Encoder` and `Decoder` do not aim to provide any interpretation of the data. |
| 109 |
|
| 110 |
Functions like `Marshal`, `MarshalWrite`, `MarshalEncode`, `Unmarshal`, |
| 111 |
`UnmarshalRead`, and `UnmarshalDecode` provide semantic meaning by correlating |
| 112 |
any arbitrary Go type with some JSON representation of that type (as stored in |
| 113 |
data types like `[]byte`, `io.Writer`, `io.Reader`, `Encoder`, or `Decoder`). |
| 114 |
|
| 115 |
 |
| 116 |
|
| 117 |
This diagram provides a high-level overview of the v2 `json` and `jsontext` packages. |
| 118 |
Purple blocks represent types, while blue blocks represent functions or methods. |
| 119 |
The arrows and their direction represent the approximate flow of data. |
| 120 |
The bottom half of the diagram contains functionality that is only concerned |
| 121 |
with syntax (implemented by the `jsontext` package), |
| 122 |
while the upper half contains functionality that assigns |
| 123 |
semantic meaning to syntactic data handled by the bottom half |
| 124 |
(as implemented by the v2 `json` package). |
| 125 |
|
| 126 |
In contrast to v1 `encoding/json`, options are represented as separate types |
| 127 |
rather than being setter methods on the `Encoder` or `Decoder` types. |
| 128 |
Some options affects JSON serialization at the syntactic layer, |
| 129 |
while others affect it at the semantic layer. |
| 130 |
Some options only affect JSON when decoding, |
| 131 |
while others affect JSON while encoding. |
| 132 |
|
| 133 |
## Behavior changes |
| 134 |
|
| 135 |
The v2 `json` package changes the default behavior of `Marshal` and `Unmarshal` |
| 136 |
relative to the v1 `json` package to be more sensible. |
| 137 |
Some of these behavior changes have options and workarounds to opt into |
| 138 |
behavior similar to what v1 provided. |
| 139 |
|
| 140 |
This table shows an overview of the changes: |
| 141 |
|
| 142 |
| v1 | v2 | Details | |
| 143 |
| -- | -- | ------- | |
| 144 |
| JSON object members are unmarshaled into a Go struct using a **case-insensitive name match**. | JSON object members are unmarshaled into a Go struct using a **case-sensitive name match**. | [CaseSensitivity](/v1/diff_test.go#:~:text=TestCaseSensitivity) | |
| 145 |
| When marshaling a Go struct, a struct field marked as `omitempty` is omitted if **the field value is an empty Go value**, which is defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string. | When marshaling a Go struct, a struct field marked as `omitempty` is omitted if **the field value would encode as an empty JSON value**, which is defined as a JSON null, or an empty JSON string, object, or array. | [OmitEmptyOption](/v1/diff_test.go#:~:text=TestOmitEmptyOption) | |
| 146 |
| The `string` option **does affect** Go strings and bools. | The `string` option **does not affect** Go strings or bools. | [StringOption](/v1/diff_test.go#:~:text=TestStringOption) | |
| 147 |
| The `string` option **does not recursively affect** sub-values of the Go field value. | The `string` option **does recursively affect** sub-values of the Go field value. | [StringOption](/v1/diff_test.go#:~:text=TestStringOption) | |
| 148 |
| The `string` option **sometimes accepts** a JSON null escaped within a JSON string. | The `string` option **never accepts** a JSON null escaped within a JSON string. | [StringOption](/v1/diff_test.go#:~:text=TestStringOption) | |
| 149 |
| A nil Go slice is marshaled as a **JSON null**. | A nil Go slice is marshaled as an **empty JSON array**. | [NilSlicesAndMaps](/v1/diff_test.go#:~:text=TestNilSlicesAndMaps) | |
| 150 |
| A nil Go map is marshaled as a **JSON null**. | A nil Go map is marshaled as an **empty JSON object**. | [NilSlicesAndMaps](/v1/diff_test.go#:~:text=TestNilSlicesAndMaps) | |
| 151 |
| A Go array may be unmarshaled from a **JSON array of any length**. | A Go array must be unmarshaled from a **JSON array of the same length**. | [Arrays](/v1/diff_test.go#:~:text=Arrays) | |
| 152 |
| A Go byte array is represented as a **JSON array of JSON numbers**. | A Go byte array is represented as a **Base64-encoded JSON string**. | [ByteArrays](/v1/diff_test.go#:~:text=TestByteArrays) | |
| 153 |
| `MarshalJSON` and `UnmarshalJSON` methods declared on a pointer receiver are **inconsistently called**. | `MarshalJSON` and `UnmarshalJSON` methods declared on a pointer receiver are **consistently called**. | [PointerReceiver](/v1/diff_test.go#:~:text=TestPointerReceiver) | |
| 154 |
| A Go map is marshaled in a **deterministic order**. | A Go map is marshaled in a **non-deterministic order**. | [MapDeterminism](/v1/diff_test.go#:~:text=TestMapDeterminism) | |
| 155 |
| JSON strings are encoded **with HTML-specific characters being escaped**. | JSON strings are encoded **without any characters being escaped** (unless necessary). | [EscapeHTML](/v1/diff_test.go#:~:text=TestEscapeHTML) | |
| 156 |
| When marshaling, invalid UTF-8 within a Go string **are silently replaced**. | When marshaling, invalid UTF-8 within a Go string **results in an error**. | [InvalidUTF8](/v1/diff_test.go#:~:text=TestInvalidUTF8) | |
| 157 |
| When unmarshaling, invalid UTF-8 within a JSON string **are silently replaced**. | When unmarshaling, invalid UTF-8 within a JSON string **results in an error**. | [InvalidUTF8](/v1/diff_test.go#:~:text=TestInvalidUTF8) | |
| 158 |
| When marshaling, **an error does not occur** if the output JSON value contains objects with duplicate names. | When marshaling, **an error does occur** if the output JSON value contains objects with duplicate names. | [DuplicateNames](/v1/diff_test.go#:~:text=TestDuplicateNames) | |
| 159 |
| When unmarshaling, **an error does not occur** if the input JSON value contains objects with duplicate names. | When unmarshaling, **an error does occur** if the input JSON value contains objects with duplicate names. | [DuplicateNames](/v1/diff_test.go#:~:text=TestDuplicateNames) | |
| 160 |
| Unmarshaling a JSON null into a non-empty Go value **inconsistently clears the value or does nothing**. | Unmarshaling a JSON null into a non-empty Go value **always clears the value**. | [MergeNull](/v1/diff_test.go#:~:text=TestMergeNull) | |
| 161 |
| Unmarshaling a JSON value into a non-empty Go value **follows inconsistent and bizarre behavior**. | Unmarshaling a JSON value into a non-empty Go value **always merges if the input is an object, and otherwise replaces**. | [MergeComposite](/v1/diff_test.go#:~:text=TestMergeComposite) | |
| 162 |
| A `time.Duration` is represented as a **JSON number containing the decimal number of nanoseconds**. | A `time.Duration` has no default representation in v2 (see [#71631](https://golang.org/issue/71631)) and results in an error. | | |
| 163 |
| A Go struct with only unexported fields **can be serialized**. | A Go struct with only unexported fields **cannot be serialized**. | [EmptyStructs](/v1/diff_test.go#:~:text=TestEmptyStructs) | |
| 164 |
|
| 165 |
See [diff_test.go](/v1/diff_test.go) for details about every change. |
| 166 |
|
| 167 |
## Performance |
| 168 |
|
| 169 |
One of the goals of the v2 module is to be more performant than v1, |
| 170 |
but not at the expense of correctness. |
| 171 |
In general, v2 is at performance parity with v1 for marshaling, |
| 172 |
but dramatically faster for unmarshaling. |
| 173 |
|
| 174 |
See https://github.com/go-json-experiment/jsonbench for benchmarks |
| 175 |
comparing v2 with v1 and a number of other popular JSON implementations. |