json只接受utf-8编码的字符,所以php的函数json_encode()的参数必须是utf-8编码
json格式:
============================
错误的json格式:
$error_json = "{ 'name': 'jack' }"; //json的分隔符只允许使用双引号,不能使用单引号
$error_json = '{ name: "jack" }'; //json键值对的"键"(冒号左边的部分),必须使用双引号
$error_json = '{ "name": "baz", }'; //最后一个值之后不能添加逗号
=============================
正确的json格式
$yes_json= '{"name":"jack"}';
PHP下的操作:
(1).json_encode()函数:将数组和对象,转换为json格式
例如:
①将键/值对数组转为json格式,将变成对象形式的json
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo "json化后arr为:".json_encode($arr);
==================================================
json化后arr为:{"a":1,"b":2,"c":3,"d":4,"e":5}
②将索引数组转为json格式,将变成数组形式的json
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
==================================================
["one","two","three"]
将索引数组强制转化成对象:
json_encode( (object)$arr );
或者
json_encode ( $arr, JSON_FORCE_OBJECT );
③将类的对象转为json格式,只保留public的字段
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';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
========================================
$ClassA = new ClassA;
$classA_json = json_encode($ClassA);
echo $classA_json;
========================================
{"public_var":"this is public_var"}
(2).json_decode()函数,将json格式的字符串转化为php变量,默认转为object对象,当传入第二个参数为true时,转为php数组
例如:
①.转为php对象
$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)
}
②.转为php数组
$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)
}
以上就介绍了PHP操作json,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。