json only accepts utf-8 encoded characters, so the parameters of php’s function json_encode() must be utf-8 encoded
json format:
============ ================
Wrong json format:
$error_json = "{ 'name': 'jack' }"; //json delimiter Only double quotes are allowed, single quotes are not allowed
$error_json = '{ name: "jack" }'; //The "key" (the part to the left of the colon) of the json key-value pair must use double quotes
$error_json = ' { "name": "baz", }'; //Comma cannot be added after the last value
========================== ====
Correct json format
$yes_json= '{"name":"jack"}';
Operation under PHP:
(1).json_encode( )Function: Convert arrays and objects to json format
For example:
①Convert array of key/value pairs to json format, which will become json in object form
$arr = array ( 'a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo "After jsonization, arr is: ".json_encode($arr);
============================================ =========
After jsonization, arr is: {"a":1,"b":2,"c":3,"d":4,"e":5}
②Convert the index array to json format, which will become json in array form
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
== ================================================
[ "one","two","three"]
Force the index array into an object:
json_encode( (object)$arr );
Or
json_encode ( $arr, JSON_FORCE_OBJECT );
③Convert the class object to json format, retaining only the public fields
class ClassA {
const ERROR_CODE = '404';
public $public_var = 'this is public_var';
private $ private_var = 'this is private_var';
protected $protected_var = 'this is protected_var'; ===============================
$ClassA = new ClassA; $classA_json = json_encode($ClassA) ;
=========================================={" public_var":"this is public_var"}
(2).json_decode() function, converts the string in json format into a php variable. By default, it is converted into an object object. When the second parameter is passed in When it is true, it will be converted into a php array
For example:
①. Converted into a php object
$json = '{"a":1,"b":2,"c":3 ,"d":4,"e":5}var_dump($json);
============================== ================object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int (2)
["c"] => int(3)["d"] => int(4) ["e"] => int(5)
}
②. Convert to php array
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode( $json, true));
array(5) { ["a"] => int(1) ["b"] => int(2)
["c"] => int(3)[ "d"] => int(4) ["e"] => int(5)
}
The above introduces the PHP operation json, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.