You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
encoding/json/v2: working group meeting minutes #76406
This issue is a record of the meeting minutes from the json/v2 working group. Please post any discussion in the json/v2 issue. See also the working group project board.
The goal of the json/v2 working group is to drive the json/v2 proposal to a decision, including addressing feedback from the community and the GOEXPERIMENT version of the package, implementing and experimenting with changes, and representing the proposal to the main proposal review committee.
I started the json/v2 working group as an experiment in a better decision-making process for large API proposals. The existing proposal review process has historically not been well-suited to such proposals and tends to leave them languishing, especially when there’s a lack of direct representation on the proposal review committee. The working group aims to address the diffusion of responsibility that can leave large proposals in limbo.
The working group is composed of both members of the Go team at Google and external contributors who have been involved in the json/v2 proposal. I intentionally kept it small to avoid a “committee effect”, and only plan to play a facilitator role myself. So this is also an experiment in more deeply involving trusted members of the Go contributor community in Go’s technical decision making.
How do we move this forward to a formal recommendation the proposal review committee can ingest?
@ChrisHines: There’s a collection of sub-issues. Some need to be resolved before finalizing the proposal, and some don’t.
@dsnet: Want to make sure the v1 reimplementation is of sufficient fidelity so there are no regressions. There are a few minor behavior changes. Finalized API review. May cut out some features for the initial release. Variadic options are unusual in std, but have proven useful compared to options structs.
@ChrisHines: I found a gap with float32 tokens that you can do at the high level, but not at the low level (jsontext).
@dsnet: There are several design issues to resolve. Some block it and some don’t. Can we add a “blocks-json-v2” tag?
@aclements: I don’t think this group needs to decide on the type-safe struct tags, but json/v2 could be valuable motivation for that.
@ChrisHines: json/v2 needs to support the untyped tags for backwards compatibility.
@ChrisHines: We added errors.As before there were generics, and then a new version with generics. People benefited from errors.As without generics, and its existence now isn’t a problem. That suggests it's not a blocker for json/v2.
@neild: If we do type-safe struct tags, we would do it for json/v2. It would be a great combined “this is what we’re doing for json” announcement. Do we hold up json/v2 by a release for struct tags? Or have one release of json/v2 with string tags?
@ChrisHines: The strings introduce lots of levels of escaping.
@ChrisHines and @dsnet: Language proposals take a long time. Wouldn’t want to delay json/v2 by several releases for that.
Posting discussion minutes
On the proposal issue or its own issue?
If we do a separate issue just for the minutes, it’s much easier for someone to subscribe to or read just the minutes. Anyone who wants to comment can easily still do so on the main proposal.
Describe the working group and process at the top.
Logistics for getting through sub-issues
Agree before meeting each week which ones we’re going to focus on for that meeting.
@aclements: A GitHub project would be useful for that.
JavaScript TC39 is working on standardizing durations, and there’s a general sense that whatever JavaScript does defines what the Internet does. The proposal is far enough along that it’s more a matter of “when” than “if”.
In a perfect world we would just align with TC39. However, TC39 Temporal.Duration can represent inexact units like “years”. If you try to perform math on two durations, it will throw RangeError, implying that Duration doesn’t have a native accurate value for nominal units.
Java’s Duration also uses TC39 and is compatible with TC39’s syntax. When parsing a string into a duration, it will reject inexact units. (It does accept “days”, which it treats as 24 hours.)
Marshalling has to pick a format (but all time.Durations are representable in TC39). Unmarshalling can support multiple (unambiguous) formats, so we could say “if it starts with PT, parse it as ISO 8601/TC39; if it looks like a number, parse it as fractional seconds.”
encoding/json today marshals as a nanosecond number. That’s a big footgun that we regret.
Keeping it as a number but changing the units would be a dangerous change.
The options seem to be
1) We could require a format tag and not have a default. It would be an error to not tag a time.Duration.
2) We could marshal as ISO 8601/TC39, and unmarshal a number as nanoseconds and a “PT” string as ISO 8601/TC39.
Changing the default representation is hazardous because someone could upgrade to json/v2 and suddenly something else in the JSON pipeline breaks. Suggests fail-fast. ISO 8601 would make sense if we didn’t have any history here, but we do.
If we make it an error now, we could empirically determine if there is a “right” default in the future.
⇒ Marshall will require a format tag.
If unmarshall sniffs the format, then it would be easy for a service to unintentionally support duration formats it didn’t intend.
If we require the format for marshalling, there’s no overhead to requiring it for unmarshall.
We could provide a fuzzy unmarshaller, which people could call.
We could support a list of format options. Marshall would always use the first format, but unmarshall would go through the list. That’s something we could add later.
Fuzzy unmarshalling is an opening for request smuggling.
Long ago, in a galaxy far, far away, this was all in one package. Then we noticed that all of the documentation distinguished between high-level and low-level things. And thus was born jsontext.
Internal exists because json/v2 can do some things more efficiently by reaching into jsontext.
We could fix this with a bunch of type aliases to internal things. That messes up documentation viewing today, but that’s something we’d like to fix anyway.
You want to see the documentation, the definition of the type, and any methods.
The existence of Internal is a bit of a smell. Shouldn’t json/v2 be able to use the public API of jsontext?
@dsnet will explore what it would look like to put this into an internal package and use type aliases. If that looks good, we’ll revisit representing this nicely in pkgsite.
Radical idea: format can already take a time package format string. What if we expanded those to support formatting UNIX seconds?
Float vs int seconds? Float carries strictly more information.
Does it have to be format:? Could it be something else that takes a printf formatter and applies it to UNIX time?
⇒ format:unix means floating point. The most obvious name should be the highest precision. We can add something in the future for int and other formats of UNIX time.
@aclements is thinking about the bigger picture of json/v2, type-safe field tags (#74472, but also #20165, #23637, and #27597), const structs (related: #6386, #70803), jsonschema, and Go union types.
Discriminators?
There are several forms.
{“kind”: string, <other fields interpreted by kind>}
{“kind”: string, “value”: <value>}
{kind: <value>}
@aclements: I feel like I mostly see the first form, in part because that’s encouraged by TypeScript’s type system.
@dsnet: Very hard to do anything with this in streaming, because the kind may not come first.
@ChrisHines: If we capture just one of the patterns, would we satisfy enough people?
With only one field filled in. You can do this today in Go, we just don’t impose that only one is filled in. Guaranteed that once you start parsing the circle, you know you’re parsing a circle. You can stream it.
What’s the well-lit path to “I want to pass a union around in JSON?” Also, I’m parsing JSON in which someone else has defined a union; how do I map that into Go?
@ChrisHines: The latter question is my experience with XML. We get all sorts of representations from customers and just have to deal with them.
@neild: If we added discriminated unions types to Go, we would need to come up with some default representation for that. But that doesn’t answer the question of how we parse some other representation.
@ChrisHines: k8s has a lot of models that represent unions in YAML aka JSON. Could we learn from that?
OpenAPI encourages the flattened model. We’re not sure what k8s is using, but here’s the spec.
@ChrisHines: It would be useful to talk with Cuelang about this; they’re deep in this space.
@neild: GetOptions is confusing me, but that's orthogonal to this proposal
Discussed performance: Computing whether an option is present costs "a couple extra nanoseconds" over ~20ns to get the option value. Some marshal/unmarshal implementations may call GetOption many times.
@neild: Are we going to want to reconsider the choice to use varargs options vs. a struct? @dsnet and @ChrisHines are happy with the current varargs.
Discussion to continue in future meetings.
@dsnet to write a benchmark that quantifies the performance improvement.
General consensus on GetOptions returning (v, ok) is idiomatic and a good API, but splitting into two funcs might be worth it if the performance gain is enough.
A sufficiently smart compiler might eliminate the performance penalty of (v, ok)?
Not sure if it's appropriate to comment here, but hopefully it might be.
There are several forms.
Another form that's very common that isn't mentioned explicitly above is to discriminate by top level type (for example string-or-stringlist), but that's often not the sole form of discriminator (often we can discriminate by top level type, then if it's a struct, some discriminator field).
FWIW I had a need to unmarshal a bunch of types like this recently, so wrote a little helper package: https://pkg.go.dev/github.com/cue-exp/jsondiscrim
It relies on an arguably horrible hack for defining constant fields as types, but that allows the unmarshaler to automatically determine the discriminator field from a set of structs and do the appropriate unmarshaling dance to unmarshal into the correct concrete type.
Another piece of prior art where I was exploring this area is https://github.com/rogpeppe/cuediscrim.
This is (as the name suggests) oriented around CUE, I learned quite a bit from it. The core entry point takes a set of disjunction values (e.g. X | Y | Z) and attempts to build a decision tree that can distinguish between them on the basis of simple criteria. It attempts discrimination by kind first, then by field value (not restricting itself to top-level fields). It considers required fields only, on the basis that optional fields are fundamentally bad discriminators.
I ran the code over all the schemas in schemastore and found some results I found interesting. In short, there are many APIs out there that don't have decent discriminators, but almost all of those are expressible as YOLO unions (that is, it might appear to be a discriminated union but actually all the individual fields can happily live together in a single-level struct without type clashes).
Happy to talk more about this subject if you like :)
@neild brought up being uncomfortable with using the setter function as the means to retrieve an option and was thinking of possibly alternative APIs. @neild will spend some time designing out what an alternative API could theoretically look like so that we can chew on a possible concrete design.
The way invalid UTF-8 is marshaled was always inconsistent in v1. Sometimes it would output as an escaped Unicode replacement rune and othertimes it would preserve the invalid bytes verbatim. In v2, the behavior would always consistently replace invalid UTF-8 with the Unicode replacement character (without escaping).
We believe the v2 behavior to be more principled and correct. The discussion was primarily about whether we should/can change v1. When v1 is implemented using v2 under the hood, it will adopt v2's behavior. If we can't change behavior, then we need to expose a v1 option or GODEBUG knob.
@neild: "Would we make this change in v1 *setting aside whatever v2 does?)"
General consensus is that we would make this change. It is more internally consistent, matches the wider JSON ecosystem, and we have prior precedence for changing the encoded output at a purely syntactic level.
It would have been ideal to make this change in v1 by itself for a release, rather than make this change alongside the introduction of json/v2 (which will inevitably introduce other possibly observable changes in v1). Unfortunately, Go 1.26 development is already frozen and we are aspirationally aiming for json/v2 to land in Go 1.26.
We decided to commit to the changed representation of invalid UTF-8 and revisit only if there are more reports that this change is causing issues.
The jsontext.Float token encodes a float with 64-bit precision. This leads to unnecessarily long outputs when trying to encode a 32-bit float (e.g., 3.1415927 vs 3.141592653589793).
@ChrisHines: "There should be first-class support in jsontext to use 32-bit encoding of floats"
@dsnet is hesitant about introducing 32-bit support since JSON in general recommends float64 (though it doesn't require it), it would be inconsistent with Int and Uint, and we would further codifying Go's unique 32-bit float representation.
(lots of discussion... floating-point numbers are complicated and things are made worse in JSON since floats are represented in machines as base-2, but in JSON as base-10; see my response for details)
We are leaning towards possibly adding a Float32 accessor and constructor.
Possibly we can also add a AppendFloat(b []byte, f float32, bits int) []byte helper function.
@aclements pinged @dsnet about considering what the json/v2 API would look like with typed struct tags
The struct tags are limited to consts, which makes sense, but Go consts are also extremely limiting. @aclements has been thinking about what typed struct tags would look like if we also expanded Go’s consts to include structs and arrays of consts and possibly funcs. @aclements asked @dsnet to consider this possibility as well.
Benchmarks show no benefit of splitting Get and Has. Get with “,ok” is perfectly normal, so let’s stick with just GetOption(...) (T, bool)
Is GetOption too clever?
@neild experiment with less cleverness: CL 736840. Not quite there; accidentally introduced an allocation somewhere and need to debug it.
Internal and external definitions of Options struct with the same underlying type so we can convert between them.
For every option there are three public symbols: A function that returns an Option value you pass variadically, an accessor method on Options, and a mutator method on Options.
@ChrisHines asked @neild to flesh this out and especially write some examples using both the current API and the proposed API.
@neild to post a public proposal for the new approach to options
Joe did a more complete analysis of float32 conversions, proving that parsing as float64 and then casting to float32 is not always identical to parsing as float32. Thus, we also want a Float32 accessor.
Everyone is in agreement that the accessor and AppendFloat are worthwhile
Regression of code that hits infinite recursion in v2 but not v1.
@dsnet: The v2 behavior looks correct. It is unclear why this isn’t infinite recursion in v1.
This is an artifact of making method calling more consistent in v2.
@ChrisHines: Do we need an option to avoid this change?
*tempType has no methods, so we don’t know how to marshal it. If nil, print null. Otherwise, deference and try to marshal that. Once dereferenced, it is a customUnmarshaller.
type myTime *time.Time will call Time’s UnmarshalJSON
@prattmic: v2 is effectively behaving the same as type myTime struct{*time.Time}. There the behavior seems more obviously correct.
@dsnet and @neild are in agreement that the new behavior is probably not desired, but it is difficult to avoid because we don’t preserve the context of how we got to a type. This missing context in this one case also implies that it’s going against normal, consistent behavior.
@neild: Is this inconsistency important enough to users to care about?
GODEBUG=jsonv1asv2: All uses of v1 API set v2 options.
If something fails, which callsite is the problem?
Use bisect tool to pinpoint the callsite.
Package to integrate with bisect is currently internal, but @rsc has a proposal to make it a public package: #67140
@dsnet: We have a tool at Tailscale that does similar on production canaries for jsonv2 options. Half of this is open source already and would love to open source the rest of it.
@neild: Can we detect this at runtime when we first process a Go type? If we see a named type T whose underlying type is *U and U is a named type, T does not have an UnmarshalJSON method, and *U or U has an UnmarshalJSON, then return an error.
@ChrisHines: It would still be nice to have a vet check because it’s static.
We could implement @neild’s condition statically, plus “T is passed to json.Unmarshal”
Let’s do the runtime check, and the vet check is nice-to-have.
Decision: This behavior change is okay as long as we can detect and report it. If it turns out not to be rare, then we can revisit.
@prattmic: We can preemptively run a vet check across the module ecosystem to look for potential findings.
@dsnet: We can add “unknown” back in a backward-compatible manner
We don’t recall anyone really advocating for “unknown” when it was introduced.
@ChrisHines: Don’t add it, because we don’t have a strong need for it, and we can add it in the future if needed.
@prattmic The ability to add back later with backwards-compatibility feels like a strong reason to remove for now.
@neild: Proto marshaling can discard unknown members, but we don’t need to support that. In protobuf, unmarshal doesn’t have the option to ignore unknown members, so you need that on marshal. In JSON, the default behavior is to ignore unknown members and you have to opt in to keeping unknown members (e.g., via “inline”)
@neild: Don’t like having both unknown and inline, which are almost identical
@neild / @ChrisHines: To avoid marshalling unknown members without unknown, you can clear out inline fields before marshalling.
In v1, marshal and unmarshal preserve nilness of maps and slices, which leads to interoperability issues when exchanging with other languages. There’s a lot of interest in never marshaling maps or slices as a JSON null. The downside of this is there’s some loss of information from Go-to-Go.
Unmarshal of a JSON null still results in a nil Go map or slice.
Question: Should unmarshal of {} or [] result in both a empty map/slice or a nil map/slice?
@ChrisHines: For slices, nil and empty slices are nearly identical when used normally, so less worried. For maps, you have to make the map before you can add to it. So this may be a panic footgun.
@ChrisHines: Most of the time you’re just reading the value you unmarshalled, for which nil and empty slice/map behave the same.
@dsnet: The input may not have that field set at all, so it could be nil anyway. That means if you’re going to mutate it, you have to nil check it anyway.
But if code does a Go round-trip it could definitely expect non-nil values.
There’s already an option flag to restore the old behavior.
@aclements: What about having everything go to empty map/slice?
@dsnet: There’s a performance implication to using an empty map. Empty slice does not require allocation.
@prattmic: An missing field will always be nil, correct?
@dsnet: Yes. If we always set nil, then you can’t distinguish between missing and empty/null. If we use empty map/slice, then you could distinguish.
@neild: There are several comments from people saying they need to distinguish whether a field was present or not. That suggests we shouldn’t map all of these cases to nil.
@neild: Current behavior (unmarshal null as a nil map-or-slice, unmarshal {} or [] as an empty, non-nil map or slice) seems good to me.
@dsnet: We don't have a great answer for how to detect presence in general.
@prattmic: We could change the default behavior to be more consistent between marshal/unmarshal by default, while still allowing users to detect presence with an unmarshal option.
@dsnet: Keeping the current behavior preserves round trip equivalence when using omitzero. Either other behavior would change output on round trip.
@dsnet: This is caused by a case where v1 had a sync.Pool of *bytes.Buffer that v2 has removed because it relies on a more complex pool of []byte.
@dsnet: Is there a chance we could ever get a generic sync.Pool so that we can use a simpler pool of just []byte without needing to allocate the slice header?
@neild: Could we put a generic Pool in an internal package.
@prattmic: Yes, if the implementation is simple, it should be a non-issue to put a generic pool in internal/sync or similar.
@neild: More generally, it would be nice to have a single bytespool to solve the problem of pooling heterogeneous sizes of byte slices one time, instead of each package trying to do so on its own.
Should we permit MarshalTo and UnmarshalFrom methods to return the SkipFunc sentinel error?
If we do, then we need to document that users should not call these methods directly, but that if they do they must check for SkipFunc.
Is it a breaking change for us to add support for new sentinel errors returned by MarshalTo and UnmarshalFrom functions?
@neild: No: because we never return these sentinel errors from encoding/json functions.
@neild: My experience is that we've often regretted not having a way for an optional method to return "this is unimplemented", and never regretted having that. So I think we should support returning SkipFunc from MarshalTo/UnmarshalFrom.
@prattmic: SkipFunc is an unusual name for an error, something like ErrSkip would be clearer.
@dsnet: io/fs has SkipDir and SkipAll error sentinels.
@ChrisHines: "Skip" is misleading me, since it sounds like we're skipping encoding a value but we're actually falling back to the default encoding behavior.
@dsnet: Concerned about the possibility of a MarshalTo/UnmarshalFrom func inadvertently propagating ErrUnsupported from deeper in the call stack.
@neild: I can contrive a scenario where someone writes a bug involving propagating an ErrUnsupported incorrectly, but it seems both unlikely and easy to fix.
@dsnet: I think I'm okay with dropping SkipFunc in favor of ErrUnsupported.
There are many different ways people want to customize how encoding/json handles a particular type, and satisfying each one by adding a specific feature to encoding/json isn't sustainable. A general-purpose customization mechanism like proposal: encoding/json/jsonstruct: new API for handling JSON fields in a Go struct #74819 can support many use cases, even if it's a bit less convenient for each.
None of this blocks json/v2. Once v2 is released, we can decide what additional features along these lines we want to support.
@aclements: One thing that gives me pause: I want us to think about this in the broader serialization ecosystem
@dsnet: Rust’s serde has lots of interesting ideas around how to serialize “map-like” or “list-list” types.
@aclements: I see this as connected to typed struct tags, which is in turn connected to limitations of what can be a constant in Go.
@aclements: We are good at going from a Go type as a source of truth and converting to a json type. We are much less good at taking a jsonschema as a source of truth and representing that as a Go type.
@ChrisHines: That is a perennially hard problem, with json, with XML schemas, etc. My experience is that no languages provide much support.
@ChrisHines: Considering general serialization opens the scope a lot.
@aclements: Not interested in any general format. Limited to JSON, maybe XML, etc.
@aclements: There is lots of meta information from the type that you may want to represent in the Go type system. But it can go too far; sometimes the meta information should just be in code.
@prattmic: The focus here is about expressing information from the serialization (json) type in the Go type system, not necessarily about supporting more formats.
@dsnet: When the source of truth is outside of Go, we need some form of translation layer to map to the Go type. We don’t really provide this, but with encoding/json/jsontext we provide more building blocks.
@dsnet: serde has abstraction layers for e.g., serializing map-like types.
@neild: serde splits up the object walking abstraction from the format abstraction. So you write code to serialize a “map”, but the format is unspecified. That is not what we have in Go so far.
@neild: serde is good for Rust-to-Rust communication. If you have a JSON schema that is very specific, you can’t use all of the nice serde features.
@neild: Once you get beyond TextMarshaller and BinaryMarshaller, encoding/json/v2 and database/sql require actually importing those packages to implement support for your type. Maybe we need a more generic approach that goes through a common serialization package which can later connect to json. But does this need to block json/v2?
@aclements: I’m very skeptical about doing that at all.
@dsnet: We have an accepted but unimplemented proposal for MarshalScalar which does this approach, but only for basic types. What are the reservations with the serde approach?
across many formats (map, lists), but beyond those there is lots of feature differentiation between different types (see XML, YAML cross-references).
@ChrisHines: There could also be frustrating corner cases around e.g., a format serializes in a specific order, which is inefficient w.r.t. the way the generic serialization does.
@aclements: Is container/map going to import json just to explain how to serialize the map? Maybe
@prattmic: With the serde approach, if you’re doing Rust-to-Rust, you don’t need to use the differentiated features of the formats. But that raises the question of why support all of these formats in the first place.
@ChrisHines: You would only have to import jsontext, which is pretty minimal.
@neild: I’m supposing we don’t want to import anything JSON-specific.
@ChrisHines: Could we add more interfaces in the encoding package? A MapMarshaller and a SliceMarshaller? Could you retroactively add support for those in json/v2?
@dsnet: I don’t know how that interface would actually work. Does it return an iterator over any? If it returns a concrete type, you can’t type-assert to it.
@neild: It could take an “Encoder” parameter and call methods on it.
@dsnet: There’s already divergence in what formats support, e.g., map keys.
@aclements: Are these data structures going to satisfy some interface that’s unrelated to marshalling/unmarshalling anyway?
For marshalling/unmarshalling, it almost has to flatten out to any.
@neild: Serde has a fairly large “Serializer” interface that maps to this abstract serial representation. “If you’re a type that wants to marshall itself, implement this method and represent yourself in this common data model to this interface.”
@prattmic: If container/map wanted to call this interface, it would need a huge type switch to call the right concretely typed method.
@chrishine: For concrete types, it is mostly trivial, just call AddInt, AddString, etc.
@neild: Suppose we add these generic encoding methods, would that eliminate the need for jsontext and MarshalTo/UnmarshalFrom? I think it wouldn’t because there are always going to be types that want a JSON-specific encoding.
@dsnet: Because of the feature differences between formats, I think you’re always going to want the ability to do format-specific things.
@aclements: Even limiting typed struct tags to just JSON, how do we ensure that they are general enough to support what users need from jsonschema?
@neild: Even with typed struct tags, we still need support for string struct tags for backwards compatibility.
@ChrisHines: Should we withhold new struct tags from v2 in advance of typed struct tags?
@dsnet: format has a custom format, so it would be the main contender. Other tags follow the common format.
@ChrisHines: jsonschema lets you specify much more than just the structure, such as validation. How far would we want to go in supporting all features?
@dsnet: My thought is that a jsonschema package would have its own Marshal/Unmarshal, distinct from encoding/json/v2, but would use jsontext under the hood.
1) One significant inconsistency is that the type-defined marshallers (options and methods) don’t have access to the format field tag (or field tags more generally). If we exposed that, I believe all of the default marshaling behavior could be expressed in type-defined marshalers.
Does it make sense to plumb it in via the *jsontext.Encoder/Decoder?
@dsnet: Struct tags are shallow, and don’t apply recursively. Attaching it to *jsontext.Encoder might unintentionally propagate.
@neild: We may need to add this as another parameter to MarshalerTo, which we’d have to do now, since it may technically not work to smuggle it through jsontext.Encoder.
2) One limitation of struct tags that this exposes is that they only apply to fields, so if you want to supply a format for something that’s not a struct tag, you’re out of luck. E.g., if I just want to marshal a time.Time value, I can’t control the format. Many of the json field tags only make sense in the context of a struct, but that’s not true of format. Another odd inconsistency.
As we’re thinking about more expressive struct tags, I wonder if we should be thinking about them as applying to names in general. E.g., a named type could have tags just like a named field, and just like you can convert between structs with different tags, you could convert between named types with different tags (but the same underlying type).
@neild: This also comes up for maps: people can’t control the formatting of the key or value types because they aren’t struct fields.
Also a field with type []X. Does the tag only apply to the slice or does it apply to the elements of the slice?
@dsnet: Originally the format control was much more flexible, but also much more complex, so people could express things like the format of a map key. Typed struct tags may put this back on the table.
@ChrisHines: In fmt, formatting a slice applies whatever % formatting recursively, which is interestingly different.
@aclements: Should we take typed struct tags as an opportunity to consider generalizing tags to these sorts of other cases? Over the past many years it’s become very clear that tags are hugely useful for codecs, but as currently defined they feel like a wart (requiring a string-embedding DSL, not very robust, poorly integrated with the rest of the language, etc) and are limited.
@dsnet: I’ve been working with CBOR, where it’s very useful to have per-type information. If we could put tags on types, that would resolve a lot of these issues.
@ChrisHines: The xml package kind of does a hack with the Name field to solve that problem.
@neild: I don’t think we want to do anything that’s going to block json/v2. But I do think we should consider how to tag any component of a composite type. Today the only place we can annotate a type is in the fields of a struct. But we should be able to annotate any type that’s part of another type: struct fields, map keys, slice elements, etc.
@prattmic: We could summarize that as any type expression can have a tag/annotation.
@aclements: I’ve always thought of struct tags as attached to the field name, but maybe it’s actually equivalent to think of it as attached to the type of the field.
@ChrisHines: The most common use is to give another name, so it makes sense to think of it as attached to the name.
@neild: I think annotations should be about the type system and anything beyond the type system should be out of scope.
3) A general observation is that I often implement complex mappings between wire types and Go types by unmarshaling into a “raw” type that is the Go representation of the wire type, and then manually mapping that further into my Go representation type. A lot of additional smarts around types is ultimately about reducing the need for such things. Food for thought: is there something more general here? Or maybe the “go through a raw type” is totally fine.
@ChrisHines: gokit had exactly this separation of "transport layer” types and “business logic” types. You might have many different transport types for the same business type for different transports. So there’s a long precedent for this. Though a lot of people felt it was too verbose.
The binary format focus isn’t particularly relevant to JSON, but otherwise the design is all about parsing formats with schemas you don’t control. It’s also always a bijection: encoding and decoding are described together.
A key concept is transformations which are hand-written code that perform an X → X transformation during decoding/encoding. Notably, the final Nail decoding described by the schema still applies, but transformations can do steps between the raw input and the final decoding step. A simple example in Nail is decompressing data and then continuing to parse the decompressed data (or encoding and then compressing).
@ChrisHines: Kind of reminds me sql/driver and its value conversions
@aclements: I’m not sure I like that as a precedent!
@prattmic: I see that in json with data represented in a base64 string.
@dsnet: We have a single layer version of that with Marshal/Unmarshal methods
@aclements: Though that’s dispatched entirely by the final Go type. It can’t be layered on top of some naive Go type, depending entirely on the wire representation.
@dsnet: Don't think anything we have today needs to change substantially to support structured type tags.
@neild: Do we need to do something to pass per-field tags to marshal/unmarshal functions?
@ChrisHines: Are there features we want to leave out if we think we will add structured field tags in the future?
@dsnet: Thinking about it, will present something more concrete next week.
@ChrisHines: How much of JSONv2 needs to be determined at the time of the code freeze in May vs. between the freeze and the release?
@prattmic: We would want effectively everything to be finalized by the time of the freeze.
@dsnet: Austin points out that there are certain things we can't do with string struct tags. It's okay if you can't do those things in the initial version of JSONv2, even if we do support those things via some new tag mechanism in the future.
@dsnet: Not enough time this week to discuss #77703, everyone read it and we'll discuss it next week.
@dsnet: This is a proposal which was accepted years ago. We have a newly-contributed CL implementing it for JSONv1. JSONv2 already supports it. Should we add this to the JSONv1 implementation?
@ChrisHines: If we're going to accept JSONv2 in Go 1.27, then there isn't much need to change JSONv1. If JSONv2 is going to slip to a later release, then perhaps this is worth doing in 1.27.
Consensus: Wait until closer to the 1.27 freeze to see whether JSONv2 is going to arrive in that release or not.
We failed to post minutes from Feb 26, but the topic of discussion for the last two meetings was the same so I'm combining. Both meetings have focused on the options API in general, and the new API proposed in #77703 in particular. Key points from the discussion so far:
Everybody likes being able to pass variadic options lists to Marshal/Unmarshal.
Efficiency is a question. How performant does fetching an option value need to be? The fastest approaches are an inlineable test of a bit in a bitmask. Can it be slower without compromising overall marshal/unmarshal performance? Is it important that the user-facing API be as fast as the internal one?
No consensus decision yet, we'll hopefully have some more concrete proposals to evaluate next week.
The primary topic of discussion was whether a prospective Go language change for typed struct tags should affect the API for "encoding/json/v2".
In summary, proposal: spec: typed struct tags #74472 would allow using constants for struct tags. The type of the constant provides a way to convey more application-specific information beyond just the value of the constant.
See these slides for what a hypothetical API might look like with typed struct tags. For example, imagine a type Name string declaration. A Go struct field can be annotated with json.Name("fooBar") to indicate that the JSON object member name is "fooBar".
Most JSON struct tag options have an intuitive way to represent it with typed struct tags. However, the format tag option brings notably more semantic behavior that could be affected by typed struct tags.
If we had typed struct tags, we could declare 5 string types (e.g., FloatFormat, CompositeFormat, BytesFormat, TimeFormat, and DurationFormat) for the 5 different types/kinds that "json/v2" current supports specialized formats for. The supported values of those string types would be the format values that the "json/v2" prototype current support today. This provides us a way to later support typed struct tags even if "encoding/json/v2" were to be released earlier.
Typed struct tags are functionally a way to specify options on a per-field basis. There is a semantic correlation with how we specify options on a per-call basis (i.e., the options we pass to Marshal and Unmarshal). Thus, we probably want to think about how to unify the two mechanisms. For example, you could imagine passing a BytesFormat value to Marshal to indicate that all []byte types should be formatted using base16 instead of base64. Thus, a struct tag option is also a valid Marshal call option. This isn't possible with today's prototype API since options are functions (and thus cannot possibly be used as tag options).
The big question to answer is whether the possibility of typed struct tags should affect timing of when "encoding/json/v2" is released, or any API changes in the design:
The format tag option is the most notable feature of v2 that intersects with typed struct tags. We could release v2 without support for it and present it as a compelling use case for typed struct struct tags.
Alternatively, we could release v2 with the format tag option. We have a hypothetical API we could migrate to in a backwards-compatible manner to support typed struct tags. The cost for supporting the untyped format string representation is relatively low.
As noted earlier, there is a correlation between caller-specified options and field-specified options. It would be good to unify these two. We will continue to discuss general options API in the next meeting.
Each option is declared in the internal jsonopts package as a unique type.
They are type aliased into the appropriate public package
func GetOption[T Option](Options) (T, bool)
Implemented as a giant type switch
Marshallers and Unmarshallers options are implemented in the json package and an init function teaches jsonopts about them. This keeps the nice API.
Custom options could be allowed via any (or exported method), or via a wrapper type. Custom options are perhaps rare enough that a wrapper is fine?
Performance is about the same as v2 today.
Biggest downside: go doc representation
No sorting, type aliases hide information.
@prattmic: You could use a common prefix to get all of the options grouped together.
@aclements: Per-option types looks pretty good, but it is not the most obvious way to do this. It feels weird to need type-parameterization. It’s not a bad solution, just not obvious.
@ChrisHines: I wonder if a union type would make this feel natural, as it would provide grouping. Though you’d need a slice of unions or something.
@aclements: Are Has methods the thing that makes this implementation more complicated than just a struct with fields?
@neild: We also have a more efficient bitmap representation.
@neild: It is unclear if per-option identity is something we need, or that “O(N) accessors” are bad. When outgrowing a struct with fields, it is very conventional to have a type with a Getter, Setter, and Haser. It’s not the most ergonomic, but everyone will understand how to use it.
@aclements: Typed-struct tag compatibility is intriguing. As mentioned, it does make us think that we need a way to mark whether types are allowed to be struct tags or not.
@aclements: Does this type make sense as a type tag at all? Does it only make sense on certain types?
@aclements: GraphQL directives can specify exactly which parts of the grammar a specific directive is allowed. I don’t want to go down that road.
@dsnet: It’s unfortunate that there is no obvious choice.
@prattmic: Per-option accessors is probably the most obvious, but it isn’t necessarily the clear choice.
@ChrisHines: Has there been any feedback on the option API today.
@dsnet: Most users will only pass options into the API. All three of these look identical there.
@ChrisHines: For that use case, the go doc may be the biggest difference.
@dsnet: One of the biggest downsides of the current implementation is there is not much runway for compiler improvements because GetOption has to call the setter.
@dsnet: For the left two options, nothing would prevent us from adding new types for use with typed struct tags.
@prattmic: On the other hand, maybe typed struct tags have a convention of never using a type for tags and normal Go use, in which case json would be the odd one out. It is very difficult to design things for theoretical future features with no clear design.
@neild: Typed struct tags may want a dedicated jsontags package for minimal dependencies.
@ChrisHines: Tag types will likely want very short package names to avoid the package name from dominating visually.
@neild: It’s unclear whether each option would be its own tag (@json.Deterministic) or a single tag per packages (@json.Options{Deterministic: true})
@neild: My preference is a jsonopts package with an Options type with Get/Set/Has for each option. No varargs at the Marshal level. If you want multiple options, construct an Options with multiple set and pass that to Marshal.
@dsnet: In Tailscale, about 1/3rd of calls pass options. Most are about v1/v2 compatibility, and followed by UTF-8 strictness.
@neild: For example:
var opts jsonopts.Options
opts.SetDeterministic(opts)
b, err := json.MarshalOpts(v, opts) // or maybe &opts
b, err := json.Marshal(v) // if you don't want options
@ChrisHines: In this proposal, you’ll likely write small helper functions in places where you need the same set of options.
@aclements talked with Russ about typed struct tags
Russ is generally supportive of typed struct tags. String tags have shown the value of having this metadata
Russ’ suggestion was that we GA json/v2 without any new tags. It has to be compatible with the existing string tags. Then add the new tags only as typed struct tags.
Do struct tag values need to be const? Could they be a restricted form of non-const values (e.g., struct with no pointers)
Need to be able to check if two types have the same tags
Cutting the line at “const” is at least a good starting point.
(disallow untyped constants, like 42)
Want a syntax that we could generalize to things other than struct fields
Russ’ suggestion: + as the prefix operator?
Type as the key? Type has to be unique? Makes it clear what’s mutually exclusive and makes the lookup easy.
struct {
Foo string +json.OmitEmpty +jsonschema.MaxWidth(20)
T time.Time +json.TimeFormat(time.Clock)
}
Tags on types instead of fields?
Way too out there.
GA without any new string tags?
@neild: That depends on how certain we are about typed struct tags. If they’re going to happen in 1.28, that’s probably okay.
@ChrisHines: Also, what do people really want from json/v2 tags?
@aclements: All struct tags that follow the reflect convention, are already a format (k:v) within a format (Go strings). In practice, each package that uses this introduces a syntax for “v”, so it’s a format within a format within a format. The “format” json/v2 tag is a format within a format within a format within a format.
Consensus: we should definitely not block json/v2 on struct tags.
We could leave the new tags supported as string behind GOEXPERIMENT.
@dsnet: We use a lot of these tags at Tailscale. We want “go test” to work, so if the GOEXPERIMENT is set, we use the std json/v2. If not, we use the github.com/go-json-experiment/json.
@aclements: That could keep working. Keep that split. In std json/v2, make the tags hidden behind the GOEXPERIMENT. In go-json-experiment, if the GOEXPERIMENT isn’t set, act like it’s “baked on” and support the string tags.
@neild: Whether we support these or not is a matter of degree. People already have to use string tags in json code.
@dsnet: I’d like to keep format tag in the initial GA for the sake of Tailscale, but the bespoke quoting code for string format tags is a (small) forever maintenance burden.
@dsnet: People wanted commas in field names, and custom time formats. But we could drop that from string tags and say we’ll make that possible once we have structured tags.
@neild: That I could get behind. It gets at the core reason we want structured tags: to avoid these complex nested grammars and parsers.
@dsnet: The Tailscale code base doesn’t use a single sub-quoted tag.
@neild: For commas being useful in time formats, I note that no time formats defined in the time package include a comma.
@neild: I am voting for either keeping all the format tags in json/v2 just as they are now, or keeping them and dropping only the single sub-quoted tags.
@dsnet: If we're very certain typed struct tags are going to happen, I'm okay with putting the new format tags behind a GOEXPERIMENT.
@ChrisHines: If we defer these new tags waiting for structured tags, and structured tags do not happen in a reasonable time frame, we'd want to go ahead and release the new tags (as unstructured ones).
@dsnet: Maybe the path to moving forward is understanding how much the new tags are used today. If we don't include these tags, we need to keep them still available behind a GOEXPERIMENT so people using them (like Tailscale) aren't broken. We'd also want some confidence that structured typed tags will be released soon, so we have a path forward.
@dsnet: A concern here is that GOEXPERIMENTs generally have not had wide-ranging indirect effects. If you use GOEXPERIMENT=synctest, then if you build your program without that experiment, it just fails to build. If you use a field tag that's only available with a GOEXPERIMENT, then it behaves differently at runtime if you don't use that experiment.
@neild: It seems to me that the cost of just releasing the unstructured tags is low. Even if we release the sub-quoting, that's just 80 lines of parser code that shouldn't need any ongoing maintenance.
@aclements: The freeze is in a little over a month, which means if we’re going to GA json/v2 for 1.27, the proposal needs to be wrapping up ASAP.
@dsnet will update the proposal so that everything that needs proposal review is in one place. (The Go Doc is close, but doesn’t reflect a couple of more recent but not-yet-implemented decisions.)
@aclements: I convened a group to discussion typed struct tags. Everyone is generally supportive and we need to hammer out some details. Everyone understands the idea that as long as we can say “this is coming in some form in 1.28”, that will help json/v2 decision making.
Leaning toward being very conservative at least at first.
Just typed consts (with the option to expand in the future).
@dsnet: That has a big effect on API design. If we don’t support structs, people will make a bunch of small types, and users have to repeat the package name over and over. If we do support structs from the get-go, it’s more natural to have a single “options” struct type.
Though then we tried it out and for singletons (which a lot of json/v2 tags ago) and it’s actually quite a bit noisier to use a struct. @dsnet is now good with starting with just typed consts.
Leaning toward all types must be distinct
Type-keyed lookup is very simple
Natural way to express “exclusivity”. E.g., in json/v2, IgnoreCase and StrictCase would have the same type, so you would be statically prevented from specifying both.
We considered the option of allowing tags to be attached to any type use. This would be to solve the problem of if you have []*T and want to specify whether to omitzero for a zero slice or omitzero for a nil *T. We decided against this (or even leaving the door open to this) because it affects type identity too deeply. If you were to do something like [](*T @ json.OmitZero) to tag the *T, there’s no “new” type to hang that tag of off, and at the same time you don’t want to make a new type that wouldn’t be identical to *T. However, we also hypothesized that it may be less of a problem with typed struct tags: at some point in the past, json/v2 had a mini-language for expressing this sort of thing, but part of why it was abandoned was that it was too complex to put the mini-language inside two existing levels of quoting. With typed struct tags, using a mini-language to handle this problem may be more approachable.
(Note that this is different from putting tags on type definitions. We do want to leave the door open to that. So it’s conceivable you could write type PT *T @json.OmitZero and then use []PT.)
Executive decisions
Whether to release with “format” tag support in 1.27
@aclements: Our current trajectory looks like typed struct tags will happen in 1.28. Assuming that doesn’t change in the next couple weeks, json/v2 GA in 1.27 will not support the format struct tag. It’s fine if it’s still available through GOEXPERIMENT or build tag shenanigans for an easier transition.
Options API
In the function-based approach, GetOption is very weird, but all of the weirdness is condensed into GetOption and GetOption is very rarely used by user-written code.
Not yet decided, but @aclements is leaning toward sticking with the function-based approach. As weird as it is, its weirdness is concentrated in one place that very few people will encounter, and the other approaches all have their own downsides.
@aclements: Typed struct tags are almost certainly happening for 1.28. So, let’s GA json/v2 without the “format” tag in 1.27 and add it as a typed struct tag in 1.28. Likewise, let’s GA without support for complicated field name quoting and add that as a typed struct tag. For ease of transition, we can continue to support these as string tags behind GOEXPERIMENT=jsonv2 until that time. We’ll keep “inline” and “unknown” support since they’re just flags.
@dsnet: One consequence of this is that people won’t be able to format time.Duration because we decided it wouldn’t have a default format.
@aclements: It gives TC39 another 6 months to get ratified and standardize a duration representation. 🙂
@dsnet: We should also remove the additional support for quoting names in struct tags.
@aclements: Let’s do the setter-function-based Options API with the weird GetOptions.
The Internal symbol is basically impossible to use, and it’s documented as not being covered by compatibility. If we can fix the rendering of alias docs in the future, it’s okay to remove this.
@dsnet will add a TODO to export.go explaining how we would do this better with aliases.
As soon as we’ve made any API changes we’re going to make, we should flip the GOEXPERIMENT with the promise that we’ll flip it back if the proposal doesn’t get accepted.
@aclements: If a type implements MarshalJSONTo(*jsontext.Encoder) error, can it get access to the field tags? As far as I can tell, this is the one case where there’s a fixed set of special types in json/v2 that can be affected by field tags (e.g., Format), which user-defined types cannot. E.g.,
typeCustomTimestruct { ... }
func (*CustomTime) MarshalJSONTo(enc*jsontext.Encoder) error {
// Can this get access to the field tags of "Updated" to retrieve// CustomTimeFormat?...customTimeFormat, ok:=enc.GetTag[CustomTimeFormat]() // ?
}
typeCustomTimeFormatintconst (
CustomTimeJulianCustomTimeFormat=iota
)
typeSliceOfCustomTime []CustomTimefunc (sSliceOfCustomTime) MarshalJSONTo(enc*jsontext.Encoder) error {
for_, t:=ranges {
json.MarshalEncode(enc, t) // This will clear out the tags// This will plumb the custom time format through.customTimeFormat, ok:=enc.GetTag[CustomTimeFormat]()
json.MarshalEncode(enc, t, customTimeFormat)
}
}
typeTstruct {
UpdatedCustomTime : CustomTimeJulianEvents []CustomTime : CustomTimeJulianEventsSliceOfCustomTime : CustomTimeJulian// this is probably very fiddly
}
@dsnet: Is the intent of a custom field tag to be recursive or non-recursive? Presumably most of them are non-recursive. This question applies equally to string tags today.
@prattmic: My preference would be for JSON to be opinionated here. It should say struct tags are not recursive. And if you want a recursive thing, you’re going to have to do something really fiddly and that’s okay.
Upshot: We can do this in the future without changing MarshalJSONTo. It should be possible to squirrel field tags away in the jsontext.Encoder (either in Options or a new method).
@dsnet updated the proposal text and added a list of everything that’s changed since the GOEXPERIMENT proposal (search for “Changes since proposal”)
Do we need to support rolling back to v1?
Yes. A GODEBUG would be nice, but is really hard and would require building both into every binary. The far easier alternative is that we just switch the default for the GOEXPERIMENT and people can roll back by setting GOEXPERIMENT=nojsonv2.
Bisection support for v1 to v2 semantics?
@dsnet: The “jsonsplit” package does this. We could point people to this.
Where are we on testing v1-on-v2?
Last Google run was a few weeks ago and there were only a few failures, all of which were uninteresting.
Running Google tests right now.
We can flip the default before the proposal is accepted.
API walk through
// AppendFormat formats the JSON value in src and appends it to dst// according to the specified options.// See [Value.Format] for more details about the formatting behavior.funcAppendFormat(dst, src []byte, opts...Options) ([]byte, error)
// AppendQuote appends a double-quoted JSON string literal representing src// to dst and returns the extended buffer.funcAppendQuote[Bytes~[]byte|~string](dst []byte, srcBytes) ([]byte, error)
// AppendUnquote appends the decoded interpretation of src as a// double-quoted JSON string literal to dst and returns the extended buffer.// The input src must be a JSON string without any surrounding whitespace.funcAppendUnquote[Bytes~[]byte|~string](dst []byte, srcBytes) ([]byte, error)
These three should either all use the generic thing or not.
Is there any way to “dereference” a jsontext.Pointer? Not currently, but you could imagine a Value.Find(Pointer) (Value, error) method in the future. If you’re doing this, you often want to “replace” a value, which may require more API or some slices function that can tell you where a subslice is in a bigger slice.
FormatNilSliceAsNull is a global option right now. We’ll be able to apply that on a per-field basis when we bring format back in the future
We use “merge” semantics if decoding into a struct. What are the merge semantics of decoding into a Go map? Likewise, we don’t clear the map, we only clear the keys we decode into. We’re careful duplicate detection only applies within a single input.
Is string the only struct tag that applies recursively? Yes. That seems fine for []int. If it’s on a struct does it apply to the fields? Yes. That seems really weird. Could we define a reasonable boundary? E.g., if you have []T where T is a named struct, it seems really weird that it descends into T. This is closely related to the format tag and its nesting issues.
Option: Maintain the non-recursive (and kind of weird) v1 behavior and say in the future you should use the format tag that’s more general. In v2 if you put it on something it doesn’t apply to like []int, it’s an error just like how v2 is more strict about other tags.
DECIDED ON THIS
Option: Make it a “scoped” recursion that stops at a named struct type. Rationale: Unnamed struct types have to be written right next to the field tag (ignoring aliases). Named struct types have to be written somewhere else.
If you inline a jsontext.Value or a map, does that get only the fields that didn’t go into real struct fields? Yes. During marshaling, does it detect duplicates between that inline field and the real struct fields? Yes.
Do we need MarshalFunc and UnmarshalFunc given that we have MarshalToFunc, etc? They’re nice to have for consistency and are cheap to have.
We have only a few sentinel errors in the proposal. If people need more in the future we can add them.
Tasks
@dsnet: Fix AppendFormat to be consistent with AppendQuote and AppendUnquote.
@dsnet: Update documentation on merge behavior in v1 to actually match the weird thing the implementation actually does.
@dsnet: Drop NonFatalSemanticErrors. It’s not in the implementation and can be done later.
@dsnet: Drop new string tag behavior (make it non-recursive)
@dsnet: Prepare the CL to flip the GOEXPERIMENT on by default
Issue can be closed, the remaining interactions with format can be discussed as part of a format proposal.
#79659: baseline changes SyntaxError and UnmarshalTypeError offsets
much discussion of error offsets
decoding an input that starts with an invalid character like "!" produces an error offset of 1 in 1.26, 0 in 1.27
we've found a lot of code which adjusts error offsets by 1 byte, which seems to indicate people care about the exact offset produced
@dneil: encoding/json's documentation says "error occurred after reading Offset bytes", an offset of 0 cannot be right (since how do we encounter an error without reading any bytes?)
consensus that encoding/json's offsets should not change in 1.27
should encoding/json/v2's offsets (and jsontext's offsets) be consistent with encoding/json?
should encoding/json/v2's errors include two offsets, start and end?
#79788: keep v2 and jsontext packages buildable under GOEXPERIMENT=nojsonv2
the idea is that GOEXPERIMENT=nojsonv2 would cause encoding/json to use the v1 implementation, but it would not disable explicit use of the v2 API
@prattmic: setting nojsonv2 can still break you if one of your dependencies relies on features of JSONv2 that are available via encoding/json. For example, any new feature enabled by a struct tag.
@neild: How long will GOEXPERIMENT=nojsonv2 work? I think we should remove it entirely in Go 1.28.
general consensus
@neild: Given that disabling JSONv2 is a short-term escape hatch, I don't think there's much value in changing the details of what setting GOEXPERIMENT=nojsonv2 does.
general consensus: This is just minor changes to the text of error messages. This is fine.
reflect.Type.String() is not guaranteed, either.
Post-proposal issues
We’ll revisit these once v2 is actually out.
Next steps
@aclements: Get “typed struct tags” group going again
@dsnet: Remove the jsonformat experiment flag and implement a run-time backdoor to keep go-json-experiment working for now.
@dsnet: Write Migration Overview: Draft an overview article covering the V1 to V2 migration process.
@dsnet: Draft a blog post that serves as an introduction and provides a link to the migration overview documentation.
@dsnet: Document Tailscale Migration with a follow-up blog post detailing the Tailscale migration journey and the specific tools used during the process.
This will be our final regular meeting 🎉 We’ll meet on demand if needed in the future.
Activity
aclements commentedon Nov 21, 2025
Nov 20, 2025
Attendees: @aclements @ChrisHines @dsnet @neild @prattmic
Notes
errors.Asbefore there were generics, and then a new version with generics. People benefited fromerrors.Aswithout generics, and its existence now isn’t a problem. That suggests it's not a blocker for json/v2.Action items
aclements commentedon Dec 8, 2025
Dec 4, 2025
Attendees: @aclements @ChrisHines @dsnet @neild @prattmic
Notes
intandNamedIntare both just names for the same underlying type. One isn’t “more specific” than the other.anyhandler. Handlers get called in order of registration.aclements commentedon Dec 11, 2025
Dec 11, 2025
Attendees: @aclements @ChrisHines @dsnet @neild
Notes
Internalexists because json/v2 can do some things more efficiently by reaching into jsontext.Internalis a bit of a smell. Shouldn’t json/v2 be able to use the public API of jsontext?internalpackage and use type aliases. If that looks good, we’ll revisit representing this nicely in pkgsite.format:unixas integer instead of float #73486formatcan already take a time package format string. What if we expanded those to support formatting UNIX seconds?format:? Could it be something else that takes a printf formatter and applies it to UNIX time?format:unixmeans floating point. The most obvious name should be the highest precision. We can add something in the future for int and other formats of UNIX time.aclements commentedon Dec 19, 2025
Dec 18, 2025
Attendees: @aclements @ChrisHines @dsnet @neild
Review AIs
@aclements is thinking about the bigger picture of json/v2, type-safe field tags (#74472, but also #20165, #23637, and #27597), const structs (related: #6386, #70803), jsonschema, and Go union types.
Discriminators?
@aclements example of what this could look like:
{ "Kind": "circle", "Center": ..., "Radius": 0.5 }@neild and @dsnet
{ "circle": {"center": ..., "radius": 0.5} }@aclements: Good article on the difficulty of JSON unions in Go.
{"Request": {"id": "...", "method": "...", "params": {...}}}{"type": "Request", "id": "...", "method": "...", "params": {...}}{“type”: “Request”, “value”: {"id": "...", "method": "...", "params": {...}}}(my example){"id": "...", "method": "...", "params": {...}}(YOLO unions?)#74324
SkipFuncis a strange name for an error, sounds like it's a func. Should this beErrSkipFunc?#74675
rogpeppe commentedon Dec 19, 2025
Not sure if it's appropriate to comment here, but hopefully it might be.
Another form that's very common that isn't mentioned explicitly above is to discriminate by top level type (for example string-or-stringlist), but that's often not the sole form of discriminator (often we can discriminate by top level type, then if it's a struct, some discriminator field).
FWIW I had a need to unmarshal a bunch of types like this recently, so wrote a little helper package: https://pkg.go.dev/github.com/cue-exp/jsondiscrim
It relies on an arguably horrible hack for defining constant fields as types, but that allows the unmarshaler to automatically determine the discriminator field from a set of structs and do the appropriate unmarshaling dance to unmarshal into the correct concrete type.
Another piece of prior art where I was exploring this area is https://github.com/rogpeppe/cuediscrim.
This is (as the name suggests) oriented around CUE, I learned quite a bit from it. The core entry point takes a set of disjunction values (e.g. X | Y | Z) and attempts to build a decision tree that can distinguish between them on the basis of simple criteria. It attempts discrimination by kind first, then by field value (not restricting itself to top-level fields). It considers required fields only, on the basis that optional fields are fundamentally bad discriminators.
I ran the code over all the schemas in schemastore and found some results I found interesting. In short, there are many APIs out there that don't have decent discriminators, but almost all of those are expressible as YOLO unions (that is, it might appear to be a discriminated union but actually all the individual fields can happily live together in a single-level struct without type clashes).
Happy to talk more about this subject if you like :)
dsnet commentedon Jan 9, 2026
Jan 8, 2026
Attendees: @aclements @ChrisHines @dsnet @neild @prattmic
Regarding options:
#75163
#76430
jsontext.Floattoken encodes a float with 64-bit precision. This leads to unnecessarily long outputs when trying to encode a 32-bit float (e.g.,3.1415927vs3.141592653589793).jsontextto use 32-bit encoding of floats"IntandUint, and we would further codifying Go's unique 32-bit float representation.Float32accessor and constructor.AppendFloat(b []byte, f float32, bits int) []bytehelper function.aclements commentedon Jan 22, 2026
(Sorry, forgot to post this last week)
Jan 15, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
Typed struct tags
#74675
#76430
#75361
type myTime *time.Timewill call Time’s UnmarshalJSONtype myTime struct{*time.Time}. There the behavior seems more obviously correct.aclements commentedon Jan 29, 2026
Jan 22, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
@prattmic: v2 migration debugging idea: https://pkg.go.dev/golang.org/x/tools/cmd/bisect support for encoding/json/v2
#75361
UnmarshalJSONmethod, and *U or U has anUnmarshalJSON, then return an error.#76753
#76440
#76444
prattmic commentedon Jan 29, 2026
2026-01-29
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
#77271
MarshalignoresRejectUnknownMembers,UnmarshalignoresDiscardUnknownMembers. Can we make this more symmetric?DiscardUknownMembers.#76446
{}or[]result in both a empty map/slice or a nil map/slice?{}or[]as an empty, non-nil map or slice) seems good to me.omitzero. Either other behavior would change output on round trip.#75026
sync.Poolof*bytes.Bufferthat v2 has removed because it relies on a more complex pool of[]byte.sync.Poolso that we can use a simpler pool of just[]bytewithout needing to allocate the slice header?sync/v2proposal (proposal: sync/v2: new package #71076) has a genericPool, but it is unclear when this proposal will be accepted.Poolin an internal package.internal/syncor similar.bytespoolto solve the problem of pooling heterogeneous sizes of byte slices one time, instead of each package trying to do so on its own.ChrisHines commentedon Feb 5, 2026
Feb 5, 2026
Attendees: @dsnet, @ChrisHines, @neild, @prattmic
Options: @neild still needs to file a proposal for a possible alternative to GetOptions, exposing an options struct to the user.
#74324
#77423: struct field tags for directional marshal/unmarshal
prattmic commentedon Feb 12, 2026
2026-02-12
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
What’s next?
any.formathas a custom format, so it would be the main contender. Other tags follow the common format.neild commentedon Feb 20, 2026
2026-02-19
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
@aclements: Wire type W ⇔ Go type T. Right now the following mechanisms determine this mapping:
formatfield tag.formatfield tag (or field tags more generally). If we exposed that, I believe all of the default marshaling behavior could be expressed in type-defined marshalers.formatfor something that’s not a struct tag, you’re out of luck. E.g., if I just want to marshal atime.Timevalue, I can’t control the format. Many of the json field tags only make sense in the context of a struct, but that’s not true offormat. Another odd inconsistency.[]X. Does the tag only apply to the slice or does it apply to the elements of the slice?@aclements: A fun and potentially relevant read: Nail: A Practical Tool for Parsing and Generating Data Formats (or see the talk recording)
@dsnet: Not enough time this week to discuss #77703, everyone read it and we'll discuss it next week.
#48298, Decoder.DisallowDuplicateFields:
neild commentedon Mar 5, 2026
Feb 26, 2026, Mar 5, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
We failed to post minutes from Feb 26, but the topic of discussion for the last two meetings was the same so I'm combining. Both meetings have focused on the options API in general, and the new API proposed in #77703 in particular. Key points from the discussion so far:
json.GetOptionis clever, but unidiomatic and confusing, and that we should export the internal, efficient representation of options. (This is proposal: encoding/json/v2: exported read-write aggregate Options type #77703.)No consensus decision yet, we'll hopefully have some more concrete proposals to evaluate next week.
ChrisHines commentedon Mar 12, 2026
Mar 12, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
#77666
type T = *T2
dsnet commentedon Mar 20, 2026
Mar 19, 2026
Attendees: @dsnet @aclements @ChrisHines @prattmic
The primary topic of discussion was whether a prospective Go language change for typed struct tags should affect the API for "encoding/json/v2".
type Name stringdeclaration. A Go struct field can be annotated withjson.Name("fooBar")to indicate that the JSON object member name is "fooBar".formattag option brings notably more semantic behavior that could be affected by typed struct tags.FloatFormat,CompositeFormat,BytesFormat,TimeFormat, andDurationFormat) for the 5 different types/kinds that "json/v2" current supports specialized formats for. The supported values of those string types would be the format values that the "json/v2" prototype current support today. This provides us a way to later support typed struct tags even if "encoding/json/v2" were to be released earlier.MarshalandUnmarshal). Thus, we probably want to think about how to unify the two mechanisms. For example, you could imagine passing aBytesFormatvalue toMarshalto indicate that all[]bytetypes should be formatted using base16 instead of base64. Thus, a struct tag option is also a validMarshalcall option. This isn't possible with today's prototype API since options are functions (and thus cannot possibly be used as tag options).formattag option is the most notable feature of v2 that intersects with typed struct tags. We could release v2 without support for it and present it as a compelling use case for typed struct struct tags.formattag option. We have a hypothetical API we could migrate to in a backwards-compatible manner to support typed struct tags. The cost for supporting the untypedformatstring representation is relatively low.neild commentedon Apr 9, 2026
Mar 26, 2026
Attendees: @dsnet @aclements @ChrisHines @prattmic @neild
Slides: https://docs.google.com/presentation/d/1f1HA0tIlYRJGR1LhLUqUc1R7dyXiResuEqEe-bcR9iw
@dsnet’s typed options experiment
var opts jsonopts.Options
opts.SetDeterministic(opts)
b, err := json.MarshalOpts(v, opts) // or maybe &opts
b, err := json.Marshal(v) // if you don't want options
neild commentedon Apr 9, 2026
(Edited 2026-04-16 to fix formatting of
+code example)Apr 9, 2026
Attendees: @dsnet @aclements @ChrisHines @neild
@aclements talked with Russ about typed struct tags
+as the prefix operator?GA without any new string tags?
aclements commentedon Apr 16, 2026
Apr 16, 2026
Attendees: @dsnet @aclements @ChrisHines
@aclements: The freeze is in a little over a month, which means if we’re going to GA json/v2 for 1.27, the proposal needs to be wrapping up ASAP.
@aclements: I convened a group to discussion typed struct tags. Everyone is generally supportive and we need to hammer out some details. Everyone understands the idea that as long as we can say “this is coming in some form in 1.28”, that will help json/v2 decision making.
IgnoreCaseandStrictCasewould have the same type, so you would be statically prevented from specifying both.[]*Tand want to specify whether toomitzerofor a zero slice oromitzerofor a nil*T. We decided against this (or even leaving the door open to this) because it affects type identity too deeply. If you were to do something like[](*T @ json.OmitZero)to tag the*T, there’s no “new” type to hang that tag of off, and at the same time you don’t want to make a new type that wouldn’t be identical to*T. However, we also hypothesized that it may be less of a problem with typed struct tags: at some point in the past, json/v2 had a mini-language for expressing this sort of thing, but part of why it was abandoned was that it was too complex to put the mini-language inside two existing levels of quoting. With typed struct tags, using a mini-language to handle this problem may be more approachable.type PT *T @json.OmitZeroand then use[]PT.)Executive decisions
formatstruct tag. It’s fine if it’s still available through GOEXPERIMENT or build tag shenanigans for an easier transition.GetOptionis very weird, but all of the weirdness is condensed intoGetOptionandGetOptionis very rarely used by user-written code.aclements commentedon Apr 23, 2026
Apr 23, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
Getting to accept
time.Durationbecause we decided it wouldn’t have a default format.GetOptions.Internalsymbol is basically impossible to use, and it’s documented as not being covered by compatibility. If we can fix the rendering of alias docs in the future, it’s okay to remove this.@aclements: If a type implements
MarshalJSONTo(*jsontext.Encoder) error, can it get access to the field tags? As far as I can tell, this is the one case where there’s a fixed set of special types injson/v2that can be affected by field tags (e.g., Format), which user-defined types cannot. E.g.,@dsnet: Is the intent of a custom field tag to be recursive or non-recursive? Presumably most of them are non-recursive. This question applies equally to string tags today.
Upshot: We can do this in the future without changing
MarshalJSONTo. It should be possible to squirrel field tags away in thejsontext.Encoder(either inOptionsor a new method).aclements commentedon Apr 30, 2026
Apr 30, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
@dsnet updated the proposal text and added a list of everything that’s changed since the GOEXPERIMENT proposal (search for “Changes since proposal”)
Do we need to support rolling back to v1?
Bisection support for v1 to v2 semantics?
Where are we on testing v1-on-v2?
We can flip the default before the proposal is accepted.
API walk through
These three should either all use the generic thing or not.
Is there any way to “dereference” a
jsontext.Pointer? Not currently, but you could imagine aValue.Find(Pointer) (Value, error)method in the future. If you’re doing this, you often want to “replace” a value, which may require more API or someslicesfunction that can tell you where a subslice is in a bigger slice.FormatNilSliceAsNullis a global option right now. We’ll be able to apply that on a per-field basis when we bringformatback in the futureWe use “merge” semantics if decoding into a struct. What are the merge semantics of decoding into a Go map? Likewise, we don’t clear the map, we only clear the keys we decode into. We’re careful duplicate detection only applies within a single input.
Is
stringthe only struct tag that applies recursively? Yes. That seems fine for[]int. If it’s on a struct does it apply to the fields? Yes. That seems really weird. Could we define a reasonable boundary? E.g., if you have[]TwhereTis a named struct, it seems really weird that it descends intoT. This is closely related to theformattag and its nesting issues.formattag that’s more general. In v2 if you put it on something it doesn’t apply to like[]int, it’s an error just like how v2 is more strict about other tags.If you
inlineajsontext.Valueor amap, does that get only the fields that didn’t go into real struct fields? Yes. During marshaling, does it detect duplicates between that inline field and the real struct fields? Yes.Do we need
MarshalFuncandUnmarshalFuncgiven that we haveMarshalToFunc, etc? They’re nice to have for consistency and are cheap to have.We have only a few sentinel errors in the proposal. If people need more in the future we can add them.
Tasks
AppendFormatto be consistent withAppendQuoteandAppendUnquote.NonFatalSemanticErrors. It’s not in the implementation and can be done later.stringtag behavior (make it non-recursive)prattmic commentedon May 28, 2026
May 7, 2026
Attendees: @dsnet @aclements @ChrisHines @neild @prattmic
Go 1.27 GA
stringtag option #79065Documentation
prattmic commentedon May 28, 2026
May 28, 2026
Attendees: @dsnet @ChrisHines @neild @prattmic
#48298: add Decoder.DisallowDuplicateFields
#79451: reconsider interaction of format and string tags
formatcan be discussed as part of aformatproposal.#79659: baseline changes SyntaxError and UnmarshalTypeError offsets
aclements commentedon Jun 5, 2026
Jun 4, 2026
Attendees: @aclements @dsnet @ChrisHines @neild @prattmic
#79788: keep v2 and jsontext packages buildable under GOEXPERIMENT=nojsonv2
#79770: changes in various error messages
Post-proposal issues
Next steps
This will be our final regular meeting 🎉 We’ll meet on demand if needed in the future.