php中json_decode&json_encode

一、json_encode — 对变量进行 JSON 编码

语法:

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

        1、$value为要编码的值,且该函数只对UTF8编码的数据有效

        2、由以下常量组成的二进制掩码: JSON_HEX_QUOTJSON_HEX_TAGJSON_HEX_AMPJSON_HEX_APOS,JSON_NUMERIC_CHECKJSON_PRETTY_PRINTJSON_UNESCAPED_SLASHESJSON_FORCE_OBJECT,JSON_PRESERVE_ZERO_FRACTIONJSON_UNESCAPED_UNICODEJSON_PARTIAL_OUTPUT_ON_ERROR

        3、执行成功返回 json,失败返回 false

示例:

<?php
$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}

二、json_decode — 对 JSON 格式的字符串进行解码

语法:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

注意:

        1、$json 为待解码的数据,必须为utf8编码的数据

   2、$assoc 值为TRUE时返回数组,FALSE时返回对象;

        3、$depth 为递归深度;

        4、$option 二进制掩码,支持 JSON_BIGINT_AS_STRINGJSON_OBJECT_AS_ARRAYJSON_THROW_ON_ERROR

   5、一般只用前面两个参数,如果要数据类型的数据要加一个参数true

示例:

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

打印结果:

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)
}

两个结果看起来没多大区别,但调用里面的元素时,array和obj的方式是不同的

$ret = array('a'=>'1','b'=>'2','c'=>'3','d'=>'4','e'=>'5');
        $json = json_encode($ret);
        
        $array = json_decode($json,TRUE);
        $obj = json_decode($json);
        var_dump($array['b']);//调用数组元素
        echo '<br/>';
        var_dump($obj->c);//调用对象元素

打印结果如下:

string(1) '2'
string(1) '3'

三、精度丢失问题

示例:

<?php
$json = '{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

打印结果:

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

看第一个输出 number 字段 ,精度丢失了

解决:

JSON_BIGINT_AS_STRING 默认将大型整数转换为浮点数

猜你喜欢

转载自blog.csdn.net/spirit_8023/article/details/86288527
今日推荐