Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error embedding "\n" into a string literal

Tags:

go

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
like image 256
Hardy Avatar asked Aug 16 '16 14:08

Hardy


1 Answers

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.

like image 185
Bayta Darell Avatar answered Oct 19 '22 18:10

Bayta Darell