I'm trying to POST some JSON to a server using Go where special characters like ampersand must exist intact in the JSON string I'm sending.
http://play.golang.org/p/bPt9kl88-y
package main
import (
"fmt"
"encoding/json"
)
func main() {
type TransactionStatement struct {
Query string
}
statement := &TransactionStatement{
Query: "my query with this & that",
}
data, _ := json.Marshal(statement)
fmt.Printf("> %v", string(data))
}
Go's json.Marshal is converting certain characters like '&' to unicode. Which is great:
String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" to keep some browsers from misinterpreting JSON output as HTML. Ampersand "&" is also escaped to "\u0026" for the same reason. Blockquote
It may sound rediculous but the JSON I'm sending is for a database query using a RESTful endpoint, where this literal string will be used to perform a freetext database query - so I can't use unicode since it's interpreted literally.
So is there any way to prevent this conversion to unicode? Or will I just have to undo these replacements after the marshaling is done?
Thanks
Marshalling (sometimes spelled marshaling with a single l) is the process of transforming the memory representation of an object to a data format suitable for storage or transmission.
Reader) *Decoder is a function defined in the encoding/json package which reads a JSON input stream, stores it in the buffer of a Decoder object, and returns the Decoder object. The Decoder object can then be used to perform methods such as Decode() , More() , InputOutputOffset() , Buffered() .
The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string. As a special case, if the field tag is "-", the field is always omitted.
Golang Unmarshal Unmarshal is the contrary of marshal. It allows you to convert byte data into the original data structure. In go, unmarshaling is handled by the json. Unmarshal() method.
You can choose not to encode if you wish: https://golang.org/pkg/encoding/json/#Encoder.SetEscapeHTML
https://play.golang.org/p/gfy1WaDrEIH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With