Home  >  Article  >  Web Front-end  >  What does json format error mean?

What does json format error mean?

(*-*)浩
(*-*)浩Original
2019-06-01 13:53:2713429browse

Format error

What does json format error mean?

Since json only accepts utf-8 encoded characters, the parameters of json_encode() must be utf- 8 encoding, otherwise you will get a null character or null. When Chinese uses GB2312 encoding, or foreign languages ​​use ISO-8859-1 encoding, special attention should be paid to this point.

$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';

Executing json_decode() on these three strings will return null and report an error.

The first mistake is that the json delimiter (delimiter) only allows the use of double quotes, not single quotes. The second mistake is that the "name" (the part to the left of the colon) of the json name-value pair must use double quotes in any case. The third error is that you cannot add a trailing comma after the last value.

In addition, json can only be used to represent objects and arrays. If json_decode() is used on a string or value, null will be returned.

The format is correct, but an error is reported

The first type, character encoding problem

Since json only accepts utf-8 encoded characters, so The parameters of json_encode() must be utf-8 encoded, otherwise you will get null characters or null. When Chinese uses GB2312 encoding, or foreign languages ​​use ISO-8859-1 encoding, special attention should be paid to this point.

The second type of BOM problem

The BOM header is also called UTF-8 signature. In fact, the UTF-8 BOM has no effect on UFT-8. It is to support UTF-16 and UTF-32. The BOM just added, the BOM signature means to tell the editor what encoding the current file uses to facilitate the editor's identification. However, although the BOM is not displayed in the editor, it will generate output, just like an extra blank line. Generally, If the PHP code is edited and saved with software such as Notepad, when saving a file encoded in UTF-8, three invisible characters (0xEF 0xBB 0xBF, or BOM) will be inserted at the beginning of the file. It is a string of hidden characters used to let editors such as Notepad identify whether the file is encoded in UTF-8. (It’s unclear why the BOM header is automatically added when returning data).

/**
 * 去除bom报头
 */
public static String formatString(String s) {
if (s != null) {
  s = s.replaceAll("\ufeff", "");
}
 return s;
}

The above is the detailed content of What does json format error mean?. 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