Home >Backend Development >Golang >How to Fix \'invalid character \'ï\' looking for beginning of value\' Error When Unmarshalling JSON?

How to Fix \'invalid character \'ï\' looking for beginning of value\' Error When Unmarshalling JSON?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 14:25:12902browse

How to Fix

Invalid Character Error When Unmarshalling JSON with UTF-8 BOM

When attempting to unmarshal JSON data received from an HTTP request, you may encounter an error: "invalid character 'ï' looking for beginning of value."

This error arises when the server sends a UTF-8 text string that includes a Byte Order Mark (BOM). The BOM indicates the encoding type but should be stripped before decoding.

Solution:

Remove the BOM from the JSON data by using the following code:

body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) // Or []byte{239, 187, 191}

It's important to note that the UTF-8 BOM interpreted as an ISO-8859-1 string produces the characters , explaining the "ï" character in the error message.

By removing the BOM, the data can be successfully unmarshalled into the desired data structure (the TransformTextResponse in this case).

The above is the detailed content of How to Fix \'invalid character \'ï\' looking for beginning of value\' Error When Unmarshalling JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn