json_decode使用注意事项

本文介绍了 PHP 中 json_decode 函数的使用方法及注意事项,包括 JSON 字符串的正确格式要求、与 JavaScript 的区别等。
    json_decode — Decodes a JSON string


    Description


    mixed json_decode ( string $json [, bool $assoc ] )

    Takes a JSON encoded string and converts it into a PHP variable.


    Parameters

    $json  The json string being decoded.

    $assoc  When TRUE, returned objects will be converted into associative arrays.


    Return Values

    Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.


php中的json定义较之js更为严谨,遵守json的规范,所以熟练在js中使用并不等于可以在php中运用一样的规则,下面是需要注意的地方:
1、不能使用单引号来引pair,如

 

print_r(json_decode(’[0,{"a":"a","b":"b"},2,3]’)); //works
print_r(json_decode("[0,{’a':’a',’b':’b'},2,3]")); //doesn’t work

 

2、和js不一样,不允许末端有多余的逗号

print_r(json_decode(’[0,1 ]’)); //works
print_r(json_decode(’[0,1,]’)); //doesn’t work

 

3、pair中的键值也必须用双引号引起来

{ bar: “baz” } //js中这样写是可以的
{ “bar": “baz” } //php中必须要用双引号

 

4、Take care that json_decode() returns UTF8 encoded strings, whereas PHP normally works with iso-8859-1 characters.

$php_vlaues = utf8_decode(json_decode($somedata));

 

你可以使用json格式验证工具:
http://www.jsonlint.com/

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值