PHP操作json

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值