【问题标题】:php json_decode skippes some keysphp json_decode 跳过了一些键
【发布时间】:2013-07-24 03:49:02
【问题描述】:

这是要解码的 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”键值。

为什么???

【问题讨论】:

  • 在做json_decode之前检查数据是否存在EXTRA。
  • jsonlint.com 说这个 json 无效?
  • 'EXTRA':320 部分是价格对象中的最后一个值时,您有一个逗号
  • 逗号是我在 stackoverflow 上的输入错误.. 已纠正..
  • jslit 说有效

标签: php json


【解决方案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
                        )

                )

        )

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多