Error "invalid character 'ï' looking for beginning of value" when using json.Unmarshal
When attempting to parse JSON data received from an HTTP request using Golang's json.Unmarshal function, the following error may occur:
"invalid character 'ï' looking for beginning of value"
This error typically arises when the JSON response contains a Byte Order Mark (BOM) character. A BOM identifies the encoding of a text file, and should be removed before decoding.
To resolve this issue, the BOM character can be removed from the JSON response using the following code:
body := bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) // Or []byte{239, 187, 191}
Once the BOM character is removed, the JSON response can be unmarshaled into a data structure as expected.
For example, the following code can be modified to handle a JSON response with a BOM:
body, err := ioutil.ReadAll(response.Body) defer response.Body.Close() if err != nil { return "", tracerr.Wrap(err) } // Remove BOM body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) transTransform = TransformTextResponse{} err = json.Unmarshal(body, &transTransform) if err != nil { return "", tracerr.Wrap(err) }
By removing the BOM character before parsing the JSON response, the error will be resolved and the data structure can be unmarshaled successfully.
The above is the detailed content of How to Resolve the \'invalid character \'�\' looking for beginning of value\' Error in Golang\'s json.Unmarshal?. For more information, please follow other related articles on the PHP Chinese website!