Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
proposal: 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