从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。
一、json_encode()
该函数主要用来将数组和对象,转换为json格式。先看一个数组转换的例子:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
结果为
{"a":1,"b":2,"c":3,"d":4,"e":5}
再看一个对象转换的例子:
复制代码 代码如下:
$obj->body = 'another post';
$obj->id = 21;
$obj->approved = true;
$obj->favorite_count = 1;
$obj->status = NULL;
echo json_encode($obj);
复制代码 代码如下:
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
复制代码 代码如下:
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
复制代码 代码如下:
class Foo {
const ERROR_CODE = '404′;
public $public_ex = 'this is public';
private $private_ex = 'this is private!';
protected $protected_ex = 'this should be protected';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
复制代码 代码如下:
$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;
复制代码 代码如下:
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
复制代码 代码如下:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
复制代码 代码如下:
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
复制代码 代码如下:
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';