首页 > 解决方案 > 如何要求 JSON 列表中的数据?

问题描述

如何需要列表中的数据?如何做到这一点并指定类型,例如字典?

下面是两个 JSON 示例和一个模式。根据架构,这两个 JSON 样本都是有效的。具有空列表的示例应该无法验证恕我直言。我该如何做到这一点?


from jsonschema import validate


# this is ok per the schema
{
    "mylist":[
      {
        "num_items":8,
        "freq":8.5,
        "other":2
      },
      {
        "num_items":8,
        "freq":8.5,
        "other":4
      }
    ]
}

# this should fail validation, but does not.
{
    "mylist":[

    ]
}

# schema
{
  "$schema": "http://json-schema.org/schema#",
  "type": "object",
  "properties": {
    "mylist": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "num_items": {
            "type": "integer"
          },
          "freq": {
            "type": "number"
          },
          "other": {
            "type": "integer"
          }
        },
        "required": [
          "freq",
          "num_items",
          "other"
        ]
      }
    }
  },
  "required": [
    "mylist"
  ]
}


标签: pythonjsonjsonschema

解决方案


推荐阅读