[英]how to validate json schema of the given json structure
嗨,我的 json 結構如下:
{
"datasetType": "monolingual-corpus",
"languages": {
"sourceLanguage": "hi"
},
"collectionSource": [
"http://pib.gov.in/"
],
"domain":[
"news"
],
"license": "cc-by-4.0",
"submitter": {
"name": "Project aroad",
"aboutMe": "Open source project run by aroad foundation",
"team": [
{
"name": "Navneet Kumar hegde",
"aboutMe": "NLP team lead at Project aroad"
},
{
"name": "Aswini Pradeep",
"aboutMe": "Backend team lead at Project aroad"
}
]
}
我只能使用 json 模式驗證 datasetType。 我如何驗證其他值,例如“語言”、“collectoinsource”、“提交者”。 在“提交者”中,所有字段都應該是強制性的,以及如何在“提交者”中驗證“團隊”
我用 python 編寫的代碼僅驗證“datasetType”,無法驗證剩余字段。 請幫我解決這個問題,提前致謝
試試marshmallow
。 它非常適合驗證模式。
from marshmallow import Schema, fields
class LanguageSchema(Schema):
sourceLanguage = fields.String(required=True)
class UserSchema(Schema):
name = fields.String(required=True)
aboutMe = fields.String(required=True)
class SubmitterSchema(UserSchema):
team = fields.List(fields.Nested(UserSchema()))
class ExampleSchema(Schema):
datasetType = fields.String(required=True)
languages = fields.Nested(LanguageSchema(), required=True)
collectionSource = fields.List(fields.URL, required=True)
domain = fields.List(fields.String(), required=True)
license = fields.String(required=True)
submitter = fields.Nested(SubmitterSchema(), required=True)
data = {
"datasetType": "monolingual-corpus",
"languages": {
"sourceLanguage": "hi"
},
"collectionSource": [
"http://pib.gov.in/"
],
"domain": [
"news"
],
"license": "cc-by-4.0",
"submitter": {
"name": "Project aroad",
"aboutMe": "Open source project run by aroad foundation",
"team": [
{
"name": "Navneet Kumar hegde",
"aboutMe": "NLP team lead at Project aroad"
},
{
"name": "Aswini Pradeep",
"aboutMe": "Backend team lead at Project aroad"
}
]
}
}
# initialize schema
schema = ExampleSchema()
# validate data, will throw error if data does not fit schema
validated_data = schema.load(data)
您可以使用稱為 JSON Schema 的標准和 python lib jsonschema
來驗證具有您自己的架構的 json 數據。https://python-jsonschema.readthedocs.io/en/stable/validate/
至於編寫模式和驗證您想要的內容,您有幾種方法可以做到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.