Mysql / PHP / json_encode boolean string conversion
Well, you are selecting from the database as string. So that’s what gets encoded. Use SQL true/false boolean values, which in PHP become 0/1, and cast them to PHP booleans before JSON encoding them:,The problem here is that the data returned from mysql is a string, not a boolean. If you know that it is always going to be either ‘true’ or ‘false’, you can compare it with a string literal to get the correct type:,And then later, when it is json_encoded() it will be represented as a primitive boolean, instead of a string., By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Well, you are selecting from the database as string. So that’s what gets encoded. Use SQL true / false boolean values, which in PHP become 0 / 1 , and cast them to PHP booleans before JSON encoding them:
$data['id'] = (bool)$data['id']; // 0/1 -> PHP false/true echo json_encode($data); //
Answer by Arlo Mason
Well, you are selecting from the database as string. So that’s what gets encoded. Use SQL true/false boolean values, which in PHP become 0/1, and cast them to PHP booleans before JSON encoding them:
Well, you are selecting from the database as string. So that’s what gets encoded. Use SQL true / false boolean values, which in PHP become 0 / 1 , and cast them to PHP booleans before JSON encoding them:
$data['id'] = (bool)$data['id']; // 0/1 -> PHP false/true echo json_encode($data); //
Answer by Jensen Kelley
now i get an array back with true / false as a string,if i use json_encode the result is like ,And then later, when it is json_encoded() it will be represented as a primitive boolean, instead of a string.,Of course i can run a str_replace to the json string — but i think there are alternatives isn’t it ?
Well, you are selecting from the database as string. So that’s what gets encoded. Use SQL true / false boolean values, which in PHP become 0 / 1 , and cast them to PHP booleans before JSON encoding them:
$data['id'] = (bool)$data['id']; // 0/1 -> PHP false/true echo json_encode($data); //
Answer by Kaitlyn Griffith
$person = array( "name" => "Johny Carson", "title" => "CTO" ); $personJSON=json_encode($person);//returns JSON string
Answer by Alivia Tucker
Decoding JSON data is as simple as encoding it. You can use the PHP json_decode() function to convert the JSON encoded string into appropriate PHP data type. The following example demonstrates how to decode or convert a JSON object to PHP object.,You can also force json_encode() function to return an PHP indexed array as JSON object by using the JSON_FORCE_OBJECT option, as shown in the example below:,In PHP the json_encode() function is used to encode a value to JSON format. The value being encoded can be any PHP data type except a resource, like a database or file handle. The below example demonstrates how to encode a PHP associative array into a JSON object:,JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode(), respectively. Both functions only works with UTF-8 encoded string data.
Answer by Lucille Ford
Strings produced by converting JSON values have a character set of utf8mb4 and a collation of utf8mb4_bin: , MySQL handles strings used in JSON context using the utf8mb4 character set and utf8mb4_bin collation. Strings in other character sets are converted to utf8mb4 as necessary. (For strings in the ascii or utf8 character sets, no conversion is needed because ascii and utf8 are subsets of utf8mb4.) , This ordering is equivalent to the ordering of SQL strings with collation utf8mb4_bin. Because utf8mb4_bin is a binary collation, comparison of JSON values is case-sensitive: , You can use ranges in contexts where wildcards are supported.
A JSON array contains a list of values separated by commas and enclosed within [ and ] characters:
A JSON object contains a set of key-value pairs separated by commas and enclosed within < and >characters:
As the examples illustrate, JSON arrays and objects can contain scalar values that are strings or numbers, the JSON null literal, or the JSON boolean true or false literals. Keys in JSON objects must be strings. Temporal (date, time, or datetime) scalar values are also permitted:
["12:18:29.000000", "2015-07-29", "2015-07-29 12:18:29.000000"]
Nesting is permitted within JSON array elements and JSON object key values:
Attempting to insert a value into a JSON column succeeds if the value is a valid JSON value, but fails if it is not:
mysql> CREATE TABLE t1 (jdoc JSON); Query OK, 0 rows affected (0.20 sec) mysql> INSERT INTO t1 VALUES(''); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO t1 VALUES('[1, 2,'); ERROR 3140 (22032) at line 2: Invalid JSON text: "Invalid value." at position 6 in value (or column) '[1, 2,'.
The JSON_TYPE() function expects a JSON argument and attempts to parse it into a JSON value. It returns the value’s JSON type if it is valid and produces an error otherwise:
mysql> SELECT JSON_TYPE('["a", "b", 1]'); +----------------------------+ | JSON_TYPE('["a", "b", 1]') | +----------------------------+ | ARRAY | +----------------------------+ mysql> SELECT JSON_TYPE('"hello"'); +----------------------+ | JSON_TYPE('"hello"') | +----------------------+ | STRING | +----------------------+ mysql> SELECT JSON_TYPE('hello'); ERROR 3146 (22032): Invalid data type for JSON data in argument 1 to function json_type; a JSON string or JSON type is required.
As an alternative to writing JSON values using literal strings, functions exist for composing JSON values from component elements. JSON_ARRAY() takes a (possibly empty) list of values and returns a JSON array containing those values:
mysql> SELECT JSON_ARRAY('a', 1, NOW()); +----------------------------------------+ | JSON_ARRAY('a', 1, NOW()) | +----------------------------------------+ | ["a", 1, "2015-07-27 09:43:47.000000"] | +----------------------------------------+
JSON_OBJECT() takes a (possibly empty) list of key-value pairs and returns a JSON object containing those pairs:
mysql> SELECT JSON_OBJECT('key1', 1, 'key2', 'abc'); +---------------------------------------+ | JSON_OBJECT('key1', 1, 'key2', 'abc') | +---------------------------------------+ | | +---------------------------------------+
JSON_MERGE_PRESERVE() takes two or more JSON documents and returns the combined result:
mysql> SELECT JSON_MERGE_PRESERVE('["a", 1]', ''); +-----------------------------------------------------+ | JSON_MERGE_PRESERVE('["a", 1]', '') | +-----------------------------------------------------+ | ["a", 1, ] | +-----------------------------------------------------+ 1 row in set (0.00 sec)
JSON values can be assigned to user-defined variables:
mysql> SET @j = JSON_OBJECT('key', 'value'); mysql> SELECT @j; +------------------+ | @j | +------------------+ | | +------------------+
Strings produced by converting JSON values have a character set of utf8mb4 and a collation of utf8mb4_bin :
mysql> SELECT CHARSET(@j), COLLATION(@j); +-------------+---------------+ | CHARSET(@j) | COLLATION(@j) | +-------------+---------------+ | utf8mb4 | utf8mb4_bin | +-------------+---------------+
Because utf8mb4_bin is a binary collation, comparison of JSON values is case-sensitive.
mysql> SELECT JSON_ARRAY('x') = JSON_ARRAY('X'); +-----------------------------------+ | JSON_ARRAY('x') = JSON_ARRAY('X') | +-----------------------------------+ | 0 | +-----------------------------------+
Case sensitivity also applies to the JSON null , true , and false literals, which always must be written in lowercase:
mysql> SELECT JSON_VALID('null'), JSON_VALID('Null'), JSON_VALID('NULL'); +--------------------+--------------------+--------------------+ | JSON_VALID('null') | JSON_VALID('Null') | JSON_VALID('NULL') | +--------------------+--------------------+--------------------+ | 1 | 0 | 0 | +--------------------+--------------------+--------------------+ mysql> SELECT CAST('null' AS JSON); +----------------------+ | CAST('null' AS JSON) | +----------------------+ | null | +----------------------+ 1 row in set (0.00 sec) mysql> SELECT CAST('NULL' AS JSON); ERROR 3141 (22032): Invalid JSON text in argument 1 to function cast_as_json: "Invalid value." at position 0 in 'NULL'.
Case sensitivity of the JSON literals differs from that of the SQL NULL , TRUE , and FALSE literals, which can be written in any lettercase:
mysql> SELECT ISNULL(null), ISNULL(Null), ISNULL(NULL); +--------------+--------------+--------------+ | ISNULL(null) | ISNULL(Null) | ISNULL(NULL) | +--------------+--------------+--------------+ | 1 | 1 | 1 | +--------------+--------------+--------------+
Sometimes it may be necessary or desirable to insert quote characters ( » or ‘ ) into a JSON document. Assume for this example that you want to insert some JSON objects containing strings representing sentences that state some facts about MySQL, each paired with an appropriate keyword, into a table created using the SQL statement shown here:
mysql> CREATE TABLE facts (sentence JSON);
Among these keyword-sentence pairs is this one:
mascot: The MySQL mascot is a dolphin named "Sakila".
One way to insert this as a JSON object into the facts table is to use the MySQL JSON_OBJECT() function. In this case, you must escape each quote character using a backslash, as shown here:
mysql> INSERT INTO facts VALUES > (JSON_OBJECT("mascot", "Our mascot is a dolphin named \"Sakila\"."));
This does not work in the same way if you insert the value as a JSON object literal, in which case, you must use the double backslash escape sequence, like this:
mysql> INSERT INTO facts VALUES > ('');
Using the double backslash keeps MySQL from performing escape sequence processing, and instead causes it to pass the string literal to the storage engine for processing. After inserting the JSON object in either of the ways just shown, you can see that the backslashes are present in the JSON column value by doing a simple SELECT , like this:
mysql> SELECT sentence FROM facts; +---------------------------------------------------------+ | sentence | +---------------------------------------------------------+ | | +---------------------------------------------------------+
To look up this particular sentence employing mascot as the key, you can use the column-path operator -> , as shown here:
mysql> SELECT col->"$.mascot" FROM qtest; +---------------------------------------------+ | col->"$.mascot" | +---------------------------------------------+ | "Our mascot is a dolphin named \"Sakila\"." | +---------------------------------------------+ 1 row in set (0.00 sec)
This leaves the backslashes intact, along with the surrounding quote marks. To display the desired value using mascot as the key, but without including the surrounding quote marks or any escapes, use the inline path operator ->> , like this:
mysql> SELECT sentence->>"$.mascot" FROM facts; +-----------------------------------------+ | sentence->>"$.mascot" | +-----------------------------------------+ | Our mascot is a dolphin named "Sakila". | +-----------------------------------------+
The previous example does not work as shown if the NO_BACKSLASH_ESCAPES server SQL mode is enabled. If this mode is set, a single backslash instead of double backslashes can be used to insert the JSON object literal, and the backslashes are preserved. If you use the JSON_OBJECT() function when performing the insert and this mode is set, you must alternate single and double quotes, like this:
mysql> INSERT INTO facts VALUES > (JSON_OBJECT('mascot', 'Our mascot is a dolphin named "Sakila".'));