在 PHP 语言中 json_encode 和 json_decode 对 json 格式数据和数组的操作

学习笔记 马富天 2016-12-28 10:19:28 93 1

【摘要】从 5.2 版本开始,PHP 原生提供 json_encode() 和 json_decode() 函数,前者用于编码,后者用于解码。本文讲讲在使用这两个函数的时候需要注意的一些知识点。

一、json_encode() 对 PHP 对象及数组进行 json 格式的转换

首先,PHP 对象可以转成 json 格式的数据,如下:

json数据只接受 utf-8 编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者null。当中文使用GB2312编码,或者外文使用ISO-8859-1编码的时候,这一点要特别注意。

  1. class Obj
  2. {
  3. 	public $body;
  4. 	public $id;
  5. 	public $approved;
  6. 	public $favorite_count;
  7. 	public $status;
  8. }
  9. $obj = new Obj();
  10. $obj->body           = 'another post';
  11. $obj->id             = 21;
  12. $obj->approved       = true;
  13. $obj->favorite_count = 1;
  14. $obj->status         = NULL;
  15. echo json_encode($obj);	

输出如下:

  1. {"body":"another post","id":21,"approved":true,"favorite_count":1,"status":null}

对于数组1:

  1. $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
  2. echo json_encode($arr);

输出如下:

  1. {"a":1,"b":2,"c":3,"d":4,"e":5}

对于数组2:

  1. $arr = Array('one', 'two', 'three');
  2. echo json_encode($arr);

输出:

  1. ["one","two","three"]

二、json_decode() 对 json 格式的数据进行解码,转成 PHP 对象或数组

使用 json_decode 将 json 数据转成 PHP 对象,如果 json_decode() 的第二个参数默认为空则是将其转成 PHP 对象:

  1. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
  2. $json = json_decode($json);
  3. var_dump($json);
  4. 输出如下:
  5. object(stdClass)[1]
  6.   public 'a' => int 1
  7.   public 'b' => int 2
  8.   public 'c' => int 3
  9.   public 'd' => int 4
  10.   public 'e' => int 5

使用 json_decode 将 json 数据转成 PHP 数组,则需要设置 json_decode() 的第二个参数是 true:

  1. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
  2. $json = json_decode($json,true);
  3. var_dump($json);	

输出如下:

  1. array (size=5)
  2.   'a' => int 1
  3.   'b' => int 2
  4.   'c' => int 3
  5.   'd' => int 4
  6.   'e' => int 5

三、错误的 json 格式的写法,下面三种json写法都是错的:

  1. $bad_json = "{ 'bar': 'baz' }";
  2. $bad_json = '{ bar: "baz" }';
  3. $bad_json = '{ "bar": "baz", }';

对这三个字符串执行json_decode()都将返回null,并且报错。第一个的错误是,json的分隔符(delimiter)只允许使用双引号,不能使用单引号。第二个的错误是,json名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。第三个的错误是,最后一个值之后不能添加逗号(trailing comma)。另外,json只能用来表示对象(object)和数组(array),如果对一个字符串或数值使用json_decode(),将会返回null。

  1. var_dump(json_decode("Hello World"));	//	null

版权归 马富天个人博客 所有

本文标题:《在 PHP 语言中 json_encode 和 json_decode 对 json 格式数据和数组的操作》

本文链接地址:http://www.mafutian.com/239.html

转载请务必注明出处,小生将不胜感激,谢谢! 喜欢本文或觉得本文对您有帮助,请分享给您的朋友 ^_^

0

0

上一篇《 在 ubuntu 中实现允许 root 远程登录 》 下一篇《 MySQL 的三种注释的简介 》

所有评论

  1. 首页
  2. 上一页
  3. 1
  4. 下一页
  5. 尾页
  6. 第1页
  7. 每页12条
  8. 共1页
  9. 共1条
评论审核未开启
表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情
验证码

TOP10

  • 浏览最多
  • 评论最多