encoding/json: add Encoder.EncodeToken method #40127
Currently there is a way to decode JSON token-by-token, but the JSON package does not support encoding tokens that way. It has been stated that just writing the tokens yourself is straightforward enough to do (citation needed), but it's not actually that easy to do.
Here's some code that streams JSON from input to output: https://play.golang.org/p/H6Xl_twRIyC. It's at least 50 lines of code to do the basic streaming functionality, it's easy to get wrong by forgetting to put a colon or a comma in the right place, and if you want indentation or HTML escaping, you have to do it yourself.
I propose that we add an
There would be no way to produce syntactically invalid output (other than truncating the output by not completing the encoded value). The Encoder would keep track of the current state in a stack internally.
An example: if we wanted to stream a large array of JSON objects, we could do:
A slightly more comprehensive example is here
The code to stream a set of JSON values would become considerably simpler: https://play.golang.org/p/Wec5wepCYbE
It might be useful to provide callers with a final check that their encoded value is in fact complete (that is, no final closing tokens have been omitted). To do that, the following method could be provided:
This method makes it straightforward to check that the object is complete (
As with the current
It would almost be possible to implement this without adding a method at all by changing the
The text was updated successfully, but these errors were encountered:
Thanks for the review!
I'm not deeply attached to
What's the expected flushing behavior for this feature? Do we expect that every call to
I see several reasonable semantics:
In my opinion, I think option 3 is the most reasonable. It requires no new API, and has decent performance. Tracking whether the top-level value is complete is logic the
I'm okay with this API, but I'd like to sanity check the behavior for
The documentation currently says:
Since there are no
It seems to me that:
Is that correct?
Is there an appetite to change the function name to prevent stutter? I see that