[英]Create object from JSON schema
我有以下 JSON 模式:
schema = '''{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"dogs": {
"type": "array",
"items": {"type": "string"},
"maxItems": 4
},
"gender": {
"type": "string",
"enum": ["male", "female"]
},
"deceased": {
"enum": ["yes", "no", 1, 0, "true", "false"]
}
},
"required": ["firstName", "lastName"]
} '''
使用Python3
從該模式創建對象的最佳方法是什么? 目前我正在使用https://pypi.org/project/python-jsonschema-objects/但想知道是否有更好的方法來做到這一點
如果您只想能夠轉換為類似結構的簡單類或使用“點”表示法的能力,您可以使用types.SimpleNamespace
。
您可以將其用作一個非常簡單的示例:
import json
from types import SimpleNamespace
def load_schema(schema):
def from_dict(data):
return SimpleNamespace(**{k: v if not isinstance(v, dict) else from_dict(v) for k, v in data.items()})
return from_dict(json.loads(schema))
print(load_schema(schema))
namespace(
title='Example Schema',
type='object'
properties=namespace(
firstName=namespace(type='string'),
lastName=namespace(type='string')),
age=namespace(description='Age in years', minimum=0, type='integer'),
dogs=namespace(items=namespace(type='string'), maxItems=4, type='array'),
gender=namespace(enum=['male', 'female'], type='string'),
deceased=namespace(enum=['yes', 'no', 1, 0, 'true', 'false']),
required=['firstName', 'lastName'],
)
Simpy 使用 inbuild json
包和它的字符串加載函數json.loads()
。
import json
schema = ''' ... '''
obj = json.loads(schema)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.