I need to decode a JSON string which has " " in it:
[
{"Name":"Neo", "Message":"Hi
:Hello everyone"},
{"Name":"Sam","Messsage":"Hello
Eveery
One"}
]
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
:Hello everyone\"}, {\"Name\":\"Sam\",\"Messsage\":\"Hello
Eveery
One\"}]"
var pro Person
err := json.Unmarshal([]byte(s), &pro)
if err == nil {
fmt.Printf("%+v
", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v
", err)
}
}
But I get the error:
ERROR invalid character '
' 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 to specify a newline, not an actual newline. If you use an interpreted string literal, then the
\
must be quoted with a \
. Example:
"Hello\
World"
No quoting is required in a raw string literal:
`Hello
World`
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
}
Use backtick, like this working sample code:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"Name"`
Message string `json:"Message"`
}
func main() {
s := `
[
{"Name":"Neo", "Message":"Hi
:Hello everyone"},
{"Name":"Sam", "Message":"Hello
Every
One"}
]
`
var pro []Person
err := json.Unmarshal([]byte(s), &pro)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%q
", pro)
fmt.Println()
fmt.Println(pro)
}
output:
[{"Neo" "Hi
:Hello everyone"} {"Sam" "Hello
Every
One"}]
[{Neo Hi
:Hello everyone} {Sam Hello
Every
One}]