php json_decode跳过一些键

时间:2013-07-24 03:49:03

标签: php json

这是解码的JSON:

{"somearray":[
    {
     "id":71398,
     "prices":{
         "SIMPLE":270,
         "VIP":300,
         "SOFA":540,
         "EXTRA":320
         }
    },
    {
     "id":71399,
     "prices":{
         "SIMPLE":190,
         "VIP":190,
         "SOFA":380
         }
     },
    {...}
]}

注意:某些商品的价格为“EXTRA”,而有些则没有。

根据在线JSON验证器,JSON有效。 但是当你尝试在php中解码它时

json_decode($json, true);

(true - 将数据检索为关联数组。) json_decode忽略了“EXTRA”键。

所以如果你var_dump()解码后的结果 或尝试$ item ['price'] ['EXTRA']  其中没有“EXTRA”键值。

WHY ???

1 个答案:

答案 0 :(得分:1)

当json有效时,这可以正常工作:

<?php
$json = '{"somearray":[
    {
     "id":71398,
     "prices":{
         "SIMPLE":270,
         "VIP":300,
         "SOFA":540,
         "EXTRA":320'. // There was an extra comma here.
         '}
    },
    {
     "id":71399,
     "prices":{
         "SIMPLE":190,
         "VIP":190,
         "SOFA":380
         }
     }
]}';

print_r(json_decode($json));
?>

输出:

[somearray] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 71398
                    [prices] => stdClass Object
                        (
                            [SIMPLE] => 270
                            [VIP] => 300
                            [SOFA] => 540
                            [EXTRA] => 320
                        )

                )

            [1] => stdClass Object
                (
                    [id] => 71399
                    [prices] => stdClass Object
                        (
                            [SIMPLE] => 190
                            [VIP] => 190
                            [SOFA] => 380
                        )

                )

        )