JSON unmarshal with HTML escaped strings giving "invalid character 'T' after object key:value pair" error

Viewed 1117

I am trying to unmarshal a JSON in GO that looks like this:

{
    "label": "The quick "brown fox" jumps over the "lazy dog"",
    "value": "dummy value"
}

For this, I am using following code gist:

type Response struct {
    Label    string  `json:"label,omitempty"`
    Value    string  `json:"value,omitempty"`
}

body := `{
    "label": "The quick "brown fox" jumps over the "lazy dog"",
    "value": "dummy value"
}
`

res := new(Response)
if err := json.Unmarshal([]byte(html.UnescapeString(body)), &res); err != nil {
    fmt.Printf("Error: %v", err)
} else {
    fmt.Printf("%v", res)
}

But specific with the " html escaped char, it is giving error as invalid character 'T' after object key:value pair.

https://play.golang.org/p/wzvFazO1Swx

One solution that I can apply over here:

I can add \ just before all ". So once I unescape using func UnescapeString(s string) string function it will make my label field as "The quick \"brown fox\" jumps over the \"lazy dog\"" and after that, I can easily unmarshal it without any error.

body = strings.ReplaceAll(body, """, "\\"")

https://play.golang.org/p/fD6NdJNnMvS

Please let me know if there is any other and better way I can apply over here.

1 Answers

You could implement the json.Unmarshaler interface with a custom string type that, after unmarshaling itself, does the unescaping.

type UnescapedString string

func (s *UnescapedString) UnmarshalJSON(data []byte) error {
    if err := json.Unmarshal(data, (*string)(s)); err != nil {
        return err
    }
    *s = UnescapedString(html.UnescapeString(string(*s)))
    return nil
}

https://play.golang.org/p/u-hFadUT2_S

Related