0

这是要解码的JSON:

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

注意:有些商品有“额外”价格,有些则没有。

根据在线 JSON 验证器,JSON 是有效的。但是,当您尝试在 php 中将其解码为

json_decode($json, true);

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

因此,如果您 var_dump() 解码结果或尝试 $item['prices']['EXTRA'] 将没有“EXTRA”键值。

为什么???

4

1 回答 1

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
                        )

                )

        )
于 2013-07-24T03:58:22.227 回答