使用Python验证JsonSchema中的特定值

lf3rwulv  于 2023-02-14  发布在  Python
关注(0)|答案(1)|浏览(121)

朋友们,下面给出了如何验证**“标题”字段是否必须包含值“delectus aut autem”的结构
我还想知道
gender**字段是否具有“male/female”值,我也将验证该值。

def test_get():
 response = requests.get(ENDPOINT)
 assert response.status_code == 200
 data = response.json()
 print(data)
 print(data['title'])

def test_body():
 schema = {
   "type": "object",
    "properties": {
        "id": {"type": "integer"},
        "title": {"type": "string"},
        
    },
}

 validate(instance={"id": 1, "title": "delectus aut autem"}, schema=schema)
# No error, the JSON is valid.
igsr9ssn

igsr9ssn1#

试试这个,看看它是否适合你的要求:
(you可以根据您的逻辑修改代码段,这只是一个示例,以了解您的想法)
有关如何验证字段的更多信息,请参考以下文档。
JSON模式验证

import json
import jsonschema
from jsonschema import validate

# Describe what kind of json you expect.
studentSchema = {
  "type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "title": {
      "enum": ["delectus", "aut", "autem"] 
      # put this entire string if you want to be specifc -> "delectus aut autem"
      # "enum": ["delectus aut autem"]
    },
    "gender": {
      "enum": ["male", "female"]
    }
  }
}

def validateJson(jsonData):
    try:
        validate(instance=jsonData, schema=studentSchema)
    except jsonschema.exceptions.ValidationError as err:
        return False
    return True

# Convert json to python object.
jsonData = json.loads('{"title": "delectus", "id": 1, "gender": "male"}')

# validate it
isValid = validateJson(jsonData)
if isValid:
    print(jsonData)
    print("Given JSON data is Valid")
else:
    print(jsonData)
    print("Given JSON data is InValid")

相关问题