JSON in GO with encoder and writer
If you attempt to use json.NewEncoder(w).Encode(jsonData)
where jsonData
is a []byte
containing JSON data, you’ll encounter an error. Let’s break down what would happen:
json.NewEncoder(w).Encode()
expects to encode a Go data structure into JSON.- You’re passing it
jsonData
, which is already JSON, but in the form of a[]byte
slice. - The encoder will treat this
[]byte
as a raw byte array and attempt to encode it into JSON.
The result would be something like this:
- No immediate error at compile time.
- At runtime, it will “succeed” in encoding, but not in the way you expect.
- The output will be a JSON string containing the base64-encoded version of your JSON data.
For example, if your original jsonData
contained:
The output after using json.NewEncoder(w).Encode(jsonData)
would be something like:
This is because the encoder is treating the []byte
as binary data and encoding it as a base64 string within a JSON string.
To demonstrate this behavior, here’s a small program:
Output:
Original JSON:
After incorrect encoding:
To avoid this issue:
- If you want to send the JSON as-is, use
w.Write(jsonData)
. - If you need to modify the data, first unmarshal it into a Go structure, modify it, then use
json.NewEncoder(w).Encode()
with the Go structure.
Remember, json.NewEncoder(w).Encode()
is for encoding Go data structures into JSON, not for writing pre-formatted JSON data.
Updated on