PHP 实现 JSON 数据的编码和解码操作详解

来自:网络
时间:2020-10-14
阅读:

本文实例讲述了PHP 实现 JSON 数据的编码和解码操作。分享给大家供大家参考,具体如下:

JSON 的使用场景:

  1. 数据表一个字段需要记录多个信息,如记录关于用户的其他信息 数据传输,如:API接口返回值、Ajax中实现异步加载 配置文件,如 composer.json 包管理配置文件

在 PHP 中使用 JSON:

JSON 使用最频繁的两个操作就是编码和解析数据,PHP 官方提供了以下 2 个函数实现这两个操作:

  1. json_encode() json_decode()

Encoding and Decoding

编码用于将数据绑定到特定格式。需要此过程来保持数据一致性。解码是一个反向过程,它将编码的数据还原回其原始形式。

PHP JSON Encode

使用 json_encode 将 PHP 的一些数据类型转换为 JSON 格式,函数包含 3 个参数,分别为:

将要编码的数据 带有 JSON encode 常量的选项可以反映对编码行为的影响 编码的深度限制

PHP 中预定义的 JSON 常量

JSON_FORCE_OBJECT
JSON_HEX_QUOT
JSON_HEX_TAG
JSON_HEX_AMP
JSON_HEX_APOS
JSON_INVALID_UTF8_IGNORE
JSON_INVALID_UTF8_SUBSTITUTE
JSON_NUMERIC_CHECK
JSON_PARTIAL_OUTPUT_ON_ERROR
JSON_PRESERVE_ZERO_FRACTION
JSON_PRETTY_PRINT
JSON_UNESCAPED_LINE_TERMINATORS
JSON_UNESCAPED_SLASHES
JSON_UNESCAPED_UNICODE
JSON_THROW_ON_ERROR

Example: PHP json_encode()

<?php
$input_array = array("zero","one","two");
//returns ["zero","one","two"] 

$str_json_format = json_encode($input_array);
print "JSON Formatted String:" . $str_json_format;
//returns {"0":"zero","1":"one","2":"two"}

$obj_json_format = json_encode($input_array, JSON_FORCE_OBJECT);
print "<br/><br/>JSON Object:" . $obj_json_format;
//returns [ "zero", "one", "two" ]

$strJsonFormat_with_space = json_encode($input_array, JSON_PRETTY_PRINT);
print "<br/><br/>JSON Formatted String with white space:" . $strJsonFormat_with_space;

PHP JSON Decode

这是 JSON encode 的反向操作,用于将 JSON 编码的数据转换为最初编码的 PHP数据类型。

json_decode 函数包含 4 个参数,分别为:

将要解析的 JSON 字符串 当该参数为 TRUE 时,将返回 array 而非 object 指定递归深度 JSON 常量
JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR

返回值:

返回值为 TRUE, FALSENULL
如果 json 无法被解码, 或者编码数据深度超过了递归限制的话,将会返回NULL

Example: PHP json_encode()

<?php
$str_json_array_decoded = json_decode($str_json_format);
print "<br/><br/>Resultant decoded array from JSON array:<br/>";
print "<PRE>";
print_r($str_json_array_decoded);
print "</PRE>";

$str_objJson_decoded = json_decode($obj_json_format);
print "<br/><br/>Resultant decoded object data from JSON object:<br/>";
print "<PRE>";
print_r($str_objJson_decoded);
print "</PRE>";

$str_jsonAry_decoded = json_decode($obj_json_format,true);
print "<br/><br/>Resultant decoded array data from JSON object:<br/>";
print "<PRE>";
print_r($str_jsonAry_decoded);
print "</PRE>";

注意:

  1. PHP 可以将任意数据类型转换为 JSON 格式,除了 resource data JSON 解码时,必须先去除掉字符串中的反斜杠 "\",不然会导致解析失败,可以使用 stripslashes 对字符串进行处理后,再使用 json_decode 解析

如果需要解码的 JSON 数据中包含有反斜杠 "\",应该使用如下代码进行解码:

$obj = \json_decode(stripslashes($json));

返回顶部
顶部