簡體   English   中英

如何驗證給定 json 結構的 json 模式

[英]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/

至於編寫模式和驗證您想要的內容,您有幾種方法可以做到。

  1. 要強制執行數據結構,您只需使用基本對象和數組規范。 https://json-schema.org/learn/miscellaneous-examples.html
  2. 要強制執行允許的值(即在語言中),您可以使用 enum 屬性。 https://stackoverflow.com/a/30931659/4739483

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM