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

json 的使用场景:

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

在 php 中使用 json:

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

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 时,将返回 而非
  • 指定递归深度
  • 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
  2. json 解码时,必须先去除掉字符串中的反斜杠 “\”,不然会导致解析失败,可以使用 stripslashes 对字符串进行处理后,再使用 json_decode 解析

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

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

ps:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线json代码检验、检验、美化、格式化工具:

json在线格式化工具:

在线xml/json互相转换工具:

json代码在线格式化/美化/压缩/编辑/转换工具:

c语言风格/html/css/json代码格式化美化工具: