Home >Backend Development >Golang >How to Fix \'invalid character \'ï\' looking for beginning of value\' Error in JSON Unmarshal?
A web service request to Microsoft Translator yielded an error when attempting to unmarshal JSON output using json.Unmarshal. The specific error encountered was "invalid character 'ï' looking for beginning of value."
Upon inspecting the JSON response as a string, it became evident that the data appeared valid. However, comparing the byte arrays of the response and a manually marshaled version of the expected data revealed a discrepancy.
The discrepancy was attributed to the presence of a Byte Order Mark (BOM) in the response. A BOM is a special character that identifies the encoding of a text file, in this case, UTF-8.
The BOM needs to be removed before decoding the JSON response. This can be achieved using the following line of code:
body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) // Or []byte{239, 187, 191}
The bytes.TrimPrefix function removes the BOM from the beginning of the body byte array, allowing the subsequent json.Unmarshal operation to proceed without encountering the invalid character error.
The error "invalid character 'ï' looking for beginning of value" during json.Unmarshal can be caused by a BOM in the JSON response. Removing the BOM using the bytes.TrimPrefix function resolves the issue and allows the data to be successfully unmarshaled.
The above is the detailed content of How to Fix \'invalid character \'ï\' looking for beginning of value\' Error in JSON Unmarshal?. For more information, please follow other related articles on the PHP Chinese website!