【问题标题】:Verify one layer only仅验证一层
【发布时间】:2013-08-06 13:05:03
【问题描述】:

我想验证一个持有 json 的变量只有一级简单格式。有人可以提供一个仅验证一个级别而不是多级验证的示例吗?

   <?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
isValidOnlayer($json); // True
$json = '{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
    }'
    isValidOnlayer($json); // False
?>

【问题讨论】:

  • 层可以是数组/对象/基元,还是只是一个对象?

标签: php json formatting


【解决方案1】:

你可以使用它作为你的函数的结果:

count(array_filter(json_decode($json, 1), 'is_array'))

【讨论】:

    【解决方案2】:
    $tmp = json_decode($json, true, 2); // depth=2, the array "itself" is level 1, its elements are level 2
    

    如果 $tmp 是 null 则发生错误。如果深度限制是问题json_last_error() 将返回JSON_ERROR_DEPTH

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      相关资源
      最近更新 更多