I have a io.Reader
which I get from http.Request.Body
that reads a JSON byte slice from a server.
I would like to stream this to json.NewDecoder
. However I would also like to intercept the JSON before it hits json.NewDecoder
and substitute certain parts of it. For example, the JSON string contains empty hashes "{}" which I would like to remove due to a bug in the server's JSON output.
I am currently achieving my goal using json.Unmarshal
but not using the JSON streaming parser:
data, _ := ioutil.ReadAll(r.Body)
data = bytes.Replace(data, []byte("{}"), "", -1)
json.Unmarshal(data, [my struct])
How can I achieve the same thing as above but using json.NewDecoder
so I can save the many times the above code has to parse through r.Body
's data? Here's some code using a pseudo function ReplaceStream(r io.Reader, old, new []byte)
:
reader := ReplaceStream(r.Body, []byte("{}"), "")
dec := json.NewDecoder(reader)
dec.Decode([my struct])
I know ReplaceStream
might be fairly trivial to make, but is there anything in the standard library to do this that I am unaware of?