Home >Backend Development >Golang >How to Fix \'Invalid UTF-8 Byte Order Mark in JSON Response\' from Microsoft Translator?
Invalid UTF-8 Byte Order Mark in JSON Response
While using JSON to decode a response from Microsoft Translator, you encountered an error indicating invalid characters. The JSON message contained a Unicode Byte Order Mark (BOM), represented by the character ï' (ASCII code 239), which was causing issues while unmarshalling.
Understanding Byte Order Marks
A Unicode BOM is a special character sequence that identifies the encoding of a text file. However, it is not necessary for JSON responses and can cause complications when decoding.
Resolving the Issue
To handle the invalid character error, you need to remove the BOM from the response before unmarshalling the JSON data. This can be achieved using the following code:
body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) // Or []byte{239, 187, 191}
This line removes the BOM from the beginning of the response body if it exists, allowing you to unmarshal the JSON data correctly.
Note: The error message "invalid character ï' looking for beginning of value" implies that the BOM was interpreted as an ISO-8859-1 character, which resulted in invalid characters appearing in the decoded JSON.
The above is the detailed content of How to Fix \'Invalid UTF-8 Byte Order Mark in JSON Response\' from Microsoft Translator?. For more information, please follow other related articles on the PHP Chinese website!