
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How I can create Python class from JSON object?
We can use python-jsonschema-objects which is built on top of jsonschema.The python-jsonschema-objects provide an automatic class-based binding to JSON schemas for use in Python.
We have a sample json schema as follows
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"] } '''
Converting the schema object to class
import python_jsonschema_objects as pjs builder = pjs.ObjectBuilder(schema) ns = builder.build_classes() Person = ns.ExampleSchema jack = Person(firstName="Jack", lastName="Sparrow") jack.lastName example_schema lastName=Sparrow age=None firstName=Jack
Validation −
jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0
- Related Articles
- Create array from JSON object JavaScript
- How can I preserve Python tuples with JSON?
- How to create Python dictionary from JSON input?
- How can I represent python tuple in JSON format?
- How to create an object from class in Java?
- How to return a json object from a Python function?
- How can I loop over entries in JSON using Python?
- How I can dump a Python tuple in JSON format?
- How we can create singleton class in Python?
- How to create a JSON Object using Object Model in Java?
- Create nested JSON object in PHP?
- How do I create static class data and static class methods in Python?
- How to return a JSON object from a Python function in Tkinter?
- How can I convert a bytes array into JSON format in Python?
- How to construct a JSON object from a subset of another JSON object in Java?

Advertisements