I need to decode a JSON string which has "\n" in it:
[
{"Name":"Neo", "Message":"Hi\n:Hello everyone"},
{"Name":"Sam","Messsage":"Hello\nEveery\nOne"}
]
I use the Golang code below:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Messages []string `json:"Name,omitempty"`
}
func main() {
s := "[{\"Name\":\"Neo\", \"Message\":\"Hi\n:Hello everyone\"}, {\"Name\":\"Sam\",\"Messsage\":\"Hello\nEveery\nOne\"}]"
var pro Person
err := json.Unmarshal([]byte(s), &pro)
if err == nil {
fmt.Printf("%+v\n", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v\n", err)
}
}
But I get the error:
ERROR invalid character '\n' in string literal
There are a few of issues here. The first is that newline is not allowed in a JSON string. Use the two bytes \n
to specify a newline, not an actual newline. If you use an interpreted string literal, then the \
must be quoted with a \
. Example:
"Hello\\nWorld"
No quoting is required in a raw string literal:
`Hello\nWorld`
The next issue is that JSON value is an array of object values. To handle the array, unmarshal to a slice:
var pro []Person
err := json.Unmarshal([]byte(s), &pro)
To handle the objects, define Person as a struct:
type Person struct {
Name string
Message string
}
working example on the playground.
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