options.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package json
  5. import (
  6. "fmt"
  7. "github.com/go-json-experiment/json/internal"
  8. "github.com/go-json-experiment/json/internal/jsonflags"
  9. "github.com/go-json-experiment/json/internal/jsonopts"
  10. )
  11. // Options configure [Marshal], [MarshalWrite], [MarshalEncode],
  12. // [Unmarshal], [UnmarshalRead], and [UnmarshalDecode] with specific features.
  13. // Each function takes in a variadic list of options, where properties
  14. // set in later options override the value of previously set properties.
  15. //
  16. // The Options type is identical to [encoding/json.Options] and
  17. // [encoding/json/jsontext.Options]. Options from the other packages can
  18. // be used interchangeably with functionality in this package.
  19. //
  20. // Options represent either a singular option or a set of options.
  21. // It can be functionally thought of as a Go map of option properties
  22. // (even though the underlying implementation avoids Go maps for performance).
  23. //
  24. // The constructors (e.g., [Deterministic]) return a singular option value:
  25. //
  26. // opt := Deterministic(true)
  27. //
  28. // which is analogous to creating a single entry map:
  29. //
  30. // opt := Options{"Deterministic": true}
  31. //
  32. // [JoinOptions] composes multiple options values to together:
  33. //
  34. // out := JoinOptions(opts...)
  35. //
  36. // which is analogous to making a new map and copying the options over:
  37. //
  38. // out := make(Options)
  39. // for _, m := range opts {
  40. // for k, v := range m {
  41. // out[k] = v
  42. // }
  43. // }
  44. //
  45. // [GetOption] looks up the value of options parameter:
  46. //
  47. // v, ok := GetOption(opts, Deterministic)
  48. //
  49. // which is analogous to a Go map lookup:
  50. //
  51. // v, ok := Options["Deterministic"]
  52. //
  53. // There is a single Options type, which is used with both marshal and unmarshal.
  54. // Some options affect both operations, while others only affect one operation:
  55. //
  56. // - [StringifyNumbers] affects marshaling and unmarshaling
  57. // - [Deterministic] affects marshaling only
  58. // - [FormatNilSliceAsNull] affects marshaling only
  59. // - [FormatNilMapAsNull] affects marshaling only
  60. // - [OmitZeroStructFields] affects marshaling only
  61. // - [MatchCaseInsensitiveNames] affects marshaling and unmarshaling
  62. // - [DiscardUnknownMembers] affects marshaling only
  63. // - [RejectUnknownMembers] affects unmarshaling only
  64. // - [WithMarshalers] affects marshaling only
  65. // - [WithUnmarshalers] affects unmarshaling only
  66. //
  67. // Options that do not affect a particular operation are ignored.
  68. type Options = jsonopts.Options
  69. // JoinOptions coalesces the provided list of options into a single Options.
  70. // Properties set in later options override the value of previously set properties.
  71. func JoinOptions(srcs ...Options) Options {
  72. var dst jsonopts.Struct
  73. for _, src := range srcs {
  74. dst.Join(src)
  75. }
  76. return &dst
  77. }
  78. // GetOption returns the value stored in opts with the provided setter,
  79. // reporting whether the value is present.
  80. //
  81. // Example usage:
  82. //
  83. // v, ok := json.GetOption(opts, json.Deterministic)
  84. //
  85. // Options are most commonly introspected to alter the JSON representation of
  86. // [MarshalerTo.MarshalJSONTo] and [UnmarshalerFrom.UnmarshalJSONFrom] methods, and
  87. // [MarshalToFunc] and [UnmarshalFromFunc] functions.
  88. // In such cases, the presence bit should generally be ignored.
  89. func GetOption[T any](opts Options, setter func(T) Options) (T, bool) {
  90. return jsonopts.GetOption(opts, setter)
  91. }
  92. // DefaultOptionsV2 is the full set of all options that define v2 semantics.
  93. // It is equivalent to all options under [Options], [encoding/json.Options],
  94. // and [encoding/json/jsontext.Options] being set to false or the zero value,
  95. // except for the options related to whitespace formatting.
  96. func DefaultOptionsV2() Options {
  97. return &jsonopts.DefaultOptionsV2
  98. }
  99. // StringifyNumbers specifies that numeric Go types should be marshaled
  100. // as a JSON string containing the equivalent JSON number value.
  101. // When unmarshaling, numeric Go types are parsed from a JSON string
  102. // containing the JSON number without any surrounding whitespace.
  103. //
  104. // According to RFC 8259, section 6, a JSON implementation may choose to
  105. // limit the representation of a JSON number to an IEEE 754 binary64 value.
  106. // This may cause decoders to lose precision for int64 and uint64 types.
  107. // Quoting JSON numbers as a JSON string preserves the exact precision.
  108. //
  109. // This affects either marshaling or unmarshaling.
  110. func StringifyNumbers(v bool) Options {
  111. if v {
  112. return jsonflags.StringifyNumbers | 1
  113. } else {
  114. return jsonflags.StringifyNumbers | 0
  115. }
  116. }
  117. // Deterministic specifies that the same input value will be serialized
  118. // as the exact same output bytes. Different processes of
  119. // the same program will serialize equal values to the same bytes,
  120. // but different versions of the same program are not guaranteed
  121. // to produce the exact same sequence of bytes.
  122. //
  123. // This only affects marshaling and is ignored when unmarshaling.
  124. func Deterministic(v bool) Options {
  125. if v {
  126. return jsonflags.Deterministic | 1
  127. } else {
  128. return jsonflags.Deterministic | 0
  129. }
  130. }
  131. // FormatNilSliceAsNull specifies that a nil Go slice should marshal as a
  132. // JSON null instead of the default representation as an empty JSON array
  133. // (or an empty JSON string in the case of ~[]byte).
  134. // Slice fields explicitly marked with `format:emitempty` still marshal
  135. // as an empty JSON array.
  136. //
  137. // This only affects marshaling and is ignored when unmarshaling.
  138. func FormatNilSliceAsNull(v bool) Options {
  139. if v {
  140. return jsonflags.FormatNilSliceAsNull | 1
  141. } else {
  142. return jsonflags.FormatNilSliceAsNull | 0
  143. }
  144. }
  145. // FormatNilMapAsNull specifies that a nil Go map should marshal as a
  146. // JSON null instead of the default representation as an empty JSON object.
  147. // Map fields explicitly marked with `format:emitempty` still marshal
  148. // as an empty JSON object.
  149. //
  150. // This only affects marshaling and is ignored when unmarshaling.
  151. func FormatNilMapAsNull(v bool) Options {
  152. if v {
  153. return jsonflags.FormatNilMapAsNull | 1
  154. } else {
  155. return jsonflags.FormatNilMapAsNull | 0
  156. }
  157. }
  158. // OmitZeroStructFields specifies that a Go struct should marshal in such a way
  159. // that all struct fields that are zero are omitted from the marshaled output
  160. // if the value is zero as determined by the "IsZero() bool" method if present,
  161. // otherwise based on whether the field is the zero Go value.
  162. // This is semantically equivalent to specifying the `omitzero` tag option
  163. // on every field in a Go struct.
  164. //
  165. // This only affects marshaling and is ignored when unmarshaling.
  166. func OmitZeroStructFields(v bool) Options {
  167. if v {
  168. return jsonflags.OmitZeroStructFields | 1
  169. } else {
  170. return jsonflags.OmitZeroStructFields | 0
  171. }
  172. }
  173. // MatchCaseInsensitiveNames specifies that JSON object members are matched
  174. // against Go struct fields using a case-insensitive match of the name.
  175. // Go struct fields explicitly marked with `case:strict` or `case:ignore`
  176. // always use case-sensitive (or case-insensitive) name matching,
  177. // regardless of the value of this option.
  178. //
  179. // This affects either marshaling or unmarshaling.
  180. // For marshaling, this option may alter the detection of duplicate names
  181. // (assuming [jsontext.AllowDuplicateNames] is false) from inlined fields
  182. // if it matches one of the declared fields in the Go struct.
  183. func MatchCaseInsensitiveNames(v bool) Options {
  184. if v {
  185. return jsonflags.MatchCaseInsensitiveNames | 1
  186. } else {
  187. return jsonflags.MatchCaseInsensitiveNames | 0
  188. }
  189. }
  190. // DiscardUnknownMembers specifies that marshaling should ignore any
  191. // JSON object members stored in Go struct fields dedicated to storing
  192. // unknown JSON object members.
  193. //
  194. // This only affects marshaling and is ignored when unmarshaling.
  195. func DiscardUnknownMembers(v bool) Options {
  196. if v {
  197. return jsonflags.DiscardUnknownMembers | 1
  198. } else {
  199. return jsonflags.DiscardUnknownMembers | 0
  200. }
  201. }
  202. // RejectUnknownMembers specifies that unknown members should be rejected
  203. // when unmarshaling a JSON object, regardless of whether there is a field
  204. // to store unknown members.
  205. //
  206. // This only affects unmarshaling and is ignored when marshaling.
  207. func RejectUnknownMembers(v bool) Options {
  208. if v {
  209. return jsonflags.RejectUnknownMembers | 1
  210. } else {
  211. return jsonflags.RejectUnknownMembers | 0
  212. }
  213. }
  214. // WithMarshalers specifies a list of type-specific marshalers to use,
  215. // which can be used to override the default marshal behavior for values
  216. // of particular types.
  217. //
  218. // This only affects marshaling and is ignored when unmarshaling.
  219. func WithMarshalers(v *Marshalers) Options {
  220. return (*marshalersOption)(v)
  221. }
  222. // WithUnmarshalers specifies a list of type-specific unmarshalers to use,
  223. // which can be used to override the default unmarshal behavior for values
  224. // of particular types.
  225. //
  226. // This only affects unmarshaling and is ignored when marshaling.
  227. func WithUnmarshalers(v *Unmarshalers) Options {
  228. return (*unmarshalersOption)(v)
  229. }
  230. // These option types are declared here instead of "jsonopts"
  231. // to avoid a dependency on "reflect" from "jsonopts".
  232. type (
  233. marshalersOption Marshalers
  234. unmarshalersOption Unmarshalers
  235. )
  236. func (*marshalersOption) JSONOptions(internal.NotForPublicUse) {}
  237. func (*unmarshalersOption) JSONOptions(internal.NotForPublicUse) {}
  238. // Inject support into "jsonopts" to handle these types.
  239. func init() {
  240. jsonopts.GetUnknownOption = func(src *jsonopts.Struct, zero jsonopts.Options) (any, bool) {
  241. switch zero.(type) {
  242. case *marshalersOption:
  243. if !src.Flags.Has(jsonflags.Marshalers) {
  244. return (*Marshalers)(nil), false
  245. }
  246. return src.Marshalers.(*Marshalers), true
  247. case *unmarshalersOption:
  248. if !src.Flags.Has(jsonflags.Unmarshalers) {
  249. return (*Unmarshalers)(nil), false
  250. }
  251. return src.Unmarshalers.(*Unmarshalers), true
  252. default:
  253. panic(fmt.Sprintf("unknown option %T", zero))
  254. }
  255. }
  256. jsonopts.JoinUnknownOption = func(dst *jsonopts.Struct, src jsonopts.Options) {
  257. switch src := src.(type) {
  258. case *marshalersOption:
  259. dst.Flags.Set(jsonflags.Marshalers | 1)
  260. dst.Marshalers = (*Marshalers)(src)
  261. case *unmarshalersOption:
  262. dst.Flags.Set(jsonflags.Unmarshalers | 1)
  263. dst.Unmarshalers = (*Unmarshalers)(src)
  264. default:
  265. panic(fmt.Sprintf("unknown option %T", src))
  266. }
  267. }
  268. }