### Install GenSON using pip Source: https://github.com/wolverdude/genson/blob/master/README.rst This command installs the GenSON library using pip, the Python package installer. Ensure you have Python and pip installed on your system. ```bash pip install genson ``` -------------------------------- ### GenSON CLI Usage Example Source: https://github.com/wolverdude/genson/blob/master/README.rst An example of the GenSON CLI usage, showing the command structure for generating a unified JSON Schema from multiple JSON objects or schemas. It details positional and optional arguments for file input, delimiters, encoding, indentation, and schema URIs. ```bash usage: genson [-h] [--version] [-d DELIM] [-e ENCODING] [-i SPACES] [-s SCHEMA] [-$ SCHEMA_URI] ... Generate one, unified JSON Schema from one or more JSON objects and/or JSON Schemas. Compatible with JSON-Schema Draft 4 and above. positional arguments: object Files containing JSON objects (defaults to stdin if no arguments are passed). optional arguments: -h, --help Show this help message and exit. --version Show version number and exit. -d DELIM, --delimiter DELIM Set a delimiter. Use this option if the input files contain multiple JSON objects/schemas. You can pass any string. A few cases ('newline', 'tab', 'space') will get converted to a whitespace character. If this option is omitted, the parser will try to auto-detect boundaries. -e ENCODING, --encoding ENCODING Use ENCODING instead of the default system encoding when reading files. ENCODING must be a valid codec name or alias. -i SPACES, --indent SPACES Pretty-print the output, indenting SPACES spaces. -s SCHEMA, --schema SCHEMA File containing a JSON Schema (can be specified multiple times to merge schemas). -$ SCHEMA_URI, --schema-uri SCHEMA_URI The value of the '$schema' keyword (defaults to 'http://json-schema.org/schema#' or can be specified in a schema with the -s option). If 'NULL' is passed, the "$schema" keyword will not be included in the result. ``` -------------------------------- ### Python - MinNumberSchemaBuilder Usage Example Source: https://github.com/wolverdude/genson/blob/master/README.rst Demonstrates the usage of the custom MinNumberSchemaBuilder by adding objects and generating a schema. It shows how the 'minimum' keyword is correctly included in the output schema. ```python >>> builder = MinNumberSchemaBuilder() >>> builder.add_object(5) >>> builder.add_object(7) >>> builder.to_schema() {'$schema': 'http://json-schema.org/schema#', 'type': 'integer', 'minimum': 5} >>> builder.add_object(-2) >>> builder.to_schema() {'$schema': 'http://json-schema.org/schema#', 'type': 'integer', 'minimum': -2} ``` -------------------------------- ### Generate JSON Schema from File with Genson CLI Source: https://context7.com/wolverdude/genson/llms.txt Provides examples of using the Genson command-line interface to generate JSON schemas. The basic usage involves specifying a JSON file as input. Options are available for pretty-printing the output with indentation, handling multiple JSON objects separated by delimiters (like newlines), merging schemas from multiple files, and starting the generation process with an existing schema file. ```bash # Generate schema from JSON file echo '{"name": "Alice", "age": 30}' > person.json genson person.json # Output: # { # "$schema": "http://json-schema.org/schema#", # "type": "object", # "properties": { # "name": {"type": "string"}, # "age": {"type": "integer"} # }, # "required": ["name", "age"] # } # Pretty-print with indentation genson person.json -i 2 # Multiple JSON objects with delimiter cat < data.json {"id": 1, "active": true} {"id": 2, "active": false} EOF genson data.json -d newline # Merge multiple files genson file1.json file2.json file3.json -i 2 # Start with existing schema and add objects genson -s existing-schema.json new-data.json ``` -------------------------------- ### Run Tests with Tox (Bash) Source: https://github.com/wolverdude/genson/blob/master/README.rst This command executes the test suite using Tox, which is a tool for automating Python testing. Tox will run tests against all supported Python versions installed on the machine and report coverage. ```bash $ tox ``` -------------------------------- ### Compare Schema Equality with Genson SchemaBuilder Source: https://github.com/wolverdude/genson/blob/master/README.rst This Python example illustrates how to compare two SchemaBuilder objects for equality. It shows how schemas are merged when added to each other and how equality is determined based on their content. ```python from genson import SchemaBuilder b1 = SchemaBuilder() b1.add_schema({"type": "object", "properties": { "hi": {"type": "string"}}}) b2 = SchemaBuilder() b2.add_schema({"type": "object", "properties": { "hi": {"type": "integer"}}}) b1 == b2 b1.add_schema(b2) b2.add_schema(b1) b1 == b2 b1.to_schema() ``` -------------------------------- ### GenSON Python API: SchemaBuilder Initialization and Object Addition Source: https://github.com/wolverdude/genson/blob/master/README.rst Demonstrates how to initialize a SchemaBuilder object from the GenSON library and add JSON objects to it. The builder infers the schema based on the provided objects. This is the basic setup for schema generation in Python. ```python from genson import SchemaBuilder builder = SchemaBuilder() # Add some objects to infer their schema. builder.add_object({"hi": "there"}) builder.add_object({"hi": 5}) ``` -------------------------------- ### Using patternProperties with GenSON in Python Source: https://github.com/wolverdude/genson/blob/master/README.rst Demonstrates how to utilize the `patternProperties` keyword in GenSON for object schemas. This feature requires `patternProperties` to be defined in a seed schema. The example shows adding a schema with a regex pattern and then adding objects that conform to this pattern. ```python from genson import SchemaBuilder builder = SchemaBuilder() builder.add_schema({'type': 'object', 'patternProperties': {r'^\d+$': None}}) builder.add_object({'1': 1, '2': 2, '3': 3}) print(builder.to_schema()) ``` -------------------------------- ### Generate Array Tuple Validation Schema with Genson using Seed Source: https://github.com/wolverdude/genson/blob/master/README.rst This Python example shows how to influence Genson's schema generation for arrays by providing a seed schema. By seeding with an empty array for `items`, Genson generates a schema for tuple validation, where each position has a specific type. ```python from genson import SchemaBuilder builder = SchemaBuilder() seed_schema = {'type': 'array', 'items': []} builder.add_schema(seed_schema) builder.add_object(['one', 1]) builder.to_schema() ``` -------------------------------- ### Custom Number Schema Strategy in Genson Python Source: https://context7.com/wolverdude/genson/llms.txt Details how to implement a custom schema strategy in Genson, specifically for tracking the minimum value of numbers. This involves subclassing `genson.schema.strategies.Number`, overriding methods like `add_schema` and `add_object` to incorporate custom logic, and defining `EXTRA_STRATEGIES` in a custom SchemaBuilder. The example shows a builder that generates schemas with a 'minimum' keyword. ```python from genson import SchemaBuilder from genson.schema.strategies import Number # Define custom strategy tracking minimum value class MinNumber(Number): KEYWORDS = (*Number.KEYWORDS, 'minimum') def __init__(self, node_class): super().__init__(node_class) self.min = None def add_schema(self, schema): super().add_schema(schema) if self.min is None: self.min = schema.get('minimum') elif 'minimum' in schema: self.min = min(self.min, schema['minimum']) def add_object(self, obj): super().add_object(obj) self.min = obj if self.min is None else min(self.min, obj) def to_schema(self): schema = super().to_schema() if self.min is not None: schema['minimum'] = self.min return schema # Create custom builder class class MinNumberSchemaBuilder(SchemaBuilder): EXTRA_STRATEGIES = (MinNumber,) # Use custom builder builder = MinNumberSchemaBuilder() builder.add_object(5) builder.add_object(10) builder.add_object(3) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'integer', # 'minimum': 3 # } # Minimum updates with new values builder.add_object(1) schema = builder.to_schema() print(schema['minimum']) # Output: 1 ``` -------------------------------- ### GenSON CLI Help Source: https://github.com/wolverdude/genson/blob/master/README.rst Displays the help message for the GenSON command-line interface. This shows available options for generating JSON schemas from objects and schemas. ```bash genson --help ``` -------------------------------- ### Build and Export JSON Schema with Genson Source: https://github.com/wolverdude/genson/blob/master/README.rst This Python snippet demonstrates how to use the SchemaBuilder to create a JSON schema from an object and then export it as a formatted JSON string. It shows the initial schema and the final exported schema after processing. ```python from genson import SchemaBuilder builder = SchemaBuilder() builder.add_object({ "type": "object", "properties": { "hi": {"type": "boolean"} } }) # Export the schema as a JSON string. print(builder.to_json(indent=2)) ``` -------------------------------- ### Build JSON Schema with MinNumberSchemaBuilder (Python) Source: https://github.com/wolverdude/genson/blob/master/README.rst Demonstrates how to use MinNumberSchemaBuilder and ExclusiveMinNumberSchemaBuilder to construct JSON schemas. The ExclusiveMinNumberSchemaBuilder has stricter validation and will raise an error if None is added. ```python >>> builder = MinNumberSchemaBuilder() >>> picky_builder = ExclusiveMinNumberSchemaBuilder() >>> picky_builder.add_object(5) >>> picky_builder.to_schema() {'$schema': 'http://json-schema.org/schema#', 'type': 'integer', 'minimum': 5} >>> builder.add_object(None) # this is fine >>> picky_builder.add_object(None) # this fails genson.schema.node.SchemaGenerationError: Could not find matching schema type for object: None ``` -------------------------------- ### GenSON Python API: Merging Schemas Source: https://github.com/wolverdude/genson/blob/master/README.rst Illustrates how to merge an existing JSON schema into the SchemaBuilder. This allows GenSON to create a unified schema from multiple sources, including pre-defined schemas. ```python # Merge in another schema. builder.add_schema({ ``` -------------------------------- ### Generate JSON Schema from Python Objects Source: https://context7.com/wolverdude/genson/llms.txt Demonstrates basic JSON Schema generation by adding multiple Python dictionaries to a SchemaBuilder and then converting it to a JSON Schema. This is useful for inferring a schema from existing data. ```python from genson import SchemaBuilder # Create a builder and add objects builder = SchemaBuilder() builder.add_object({"name": "Alice", "age": 30}) builder.add_object({"name": "Bob", "age": 25}) # Generate schema schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'object', # 'properties': { # 'name': {'type': 'string'}, # 'age': {'type': 'integer'} # }, # 'required': ['name', 'age'] # } ``` -------------------------------- ### Evolve Schema Types for Evolving Data Source: https://context7.com/wolverdude/genson/llms.txt Shows how GenSON handles properties with different data types across multiple objects by creating a schema that accommodates all observed types. This is crucial when data schemas are not strictly enforced. ```python from genson import SchemaBuilder # Add objects with different types for same property builder = SchemaBuilder() builder.add_object({"value": 42}) builder.add_object({"value": "hello"}) builder.add_object({"value": True}) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'object', # 'properties': { # 'value': {'type': ['boolean', 'integer', 'string']} # }, # 'required': ['value'] # } ``` -------------------------------- ### Merge Multiple JSON Schemas Source: https://context7.com/wolverdude/genson/llms.txt Illustrates how to combine existing JSON Schemas into a single, comprehensive schema using GenSON's SchemaBuilder. It demonstrates merging schemas with differing required properties, resulting in a schema that satisfies all inputs. ```python from genson import SchemaBuilder builder = SchemaBuilder() # Add first schema builder.add_schema({ "type": "object", "properties": { "id": {"type": "integer"}, "name": {"type": "string"} }, "required": ["id"] }) # Add second schema builder.add_schema({ "type": "object", "properties": { "id": {"type": "integer"}, "email": {"type": "string"} }, "required": ["id", "email"] }) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'object', # 'properties': { # 'id': {'type': 'integer'}, # 'name': {'type': 'string'}, # 'email': {'type': 'string'} # }, # 'required': ['id'] # Only 'id' is required in both # } ``` -------------------------------- ### Read JSON Schema from Stdin with GenSON Source: https://context7.com/wolverdude/genson/llms.txt This command reads JSON data from standard input and generates a JSON Schema using GenSON. It's useful for piping data directly into the schema generation process. ```bash echo '{"test": 123}' | genson ``` -------------------------------- ### Generate JSON Schema with Custom URI using GenSON Source: https://context7.com/wolverdude/genson/llms.txt This command generates a JSON Schema from a file named 'data.json' and sets a custom schema URI. The URI is specified after the filename. ```bash genson data.json -$ "http://json-schema.org/draft-07/schema#" ``` -------------------------------- ### Python - Custom MinNumber Schema Strategy Source: https://github.com/wolverdude/genson/blob/master/README.rst Extends the Number schema strategy to track and include the minimum number encountered in the generated schema. It overrides add_schema, add_object, and to_schema methods, and defines the KEYWORDS class constant. ```python from genson import SchemaBuilder from genson.schema.strategies import Number class MinNumber(Number): # add 'minimum' to list of keywords KEYWORDS = (*Number.KEYWORDS, 'minimum') # create a new instance variable def __init__(self, node_class): super().__init__(node_class) self.min = None # capture 'minimum's from schemas def add_schema(self, schema): super().add_schema(schema) if self.min is None: self.min = schema.get('minimum') elif 'minimum' in schema: self.min = min(self.min, schema['minimum']) # adjust minimum based on the data def add_object(self, obj): super().add_object(obj) self.min = obj if self.min is None else min(self.min, obj) # include 'minimum' in the output def to_schema(self): schema = super().to_schema() schema['minimum'] = self.min return schema ``` -------------------------------- ### Generate Array Schema (Tuple Mode) Source: https://context7.com/wolverdude/genson/llms.txt Demonstrates generating an array schema in tuple mode, where each element in the array has its own distinct schema. This is achieved by seeding the builder with an empty array schema. ```python from genson import SchemaBuilder # Use seed schema for tuple mode - each position has different schema builder = SchemaBuilder() builder.add_schema({'type': 'array', 'items': []}) builder.add_object(['Alice', 30, True]) builder.add_object(['Bob', 25, False]) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'array', # 'items': [ # {'type': 'string'}, # {'type': 'integer'}, # {'type': 'boolean'} # ] # } ``` -------------------------------- ### Compare and Merge JSON Schemas with Genson Python Source: https://context7.com/wolverdude/genson/llms.txt Illustrates how to compare SchemaBuilder instances for equality and merge schemas. Builders with identical structures are considered equal. The `add_schema` method allows merging another builder's schema into the current one, combining properties and updating required fields. This is useful for building a schema from distributed data sources. ```python from genson import SchemaBuilder # Create two builders builder1 = SchemaBuilder() builder1.add_object({"name": "Alice", "age": 30}) builder2 = SchemaBuilder() builder2.add_object({"name": "Bob", "age": 25}) # Builders with same structure are equal print(builder1 == builder2) # Output: True # Merge one builder into another builder3 = SchemaBuilder() builder3.add_object({"name": "Charlie", "active": True}) builder1.add_schema(builder3) schema = builder1.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'object', # 'properties': { # 'name': {'type': 'string'}, # 'age': {'type': 'integer'}, # 'active': {'type': 'boolean'} # }, # 'required': ['name'] # Only 'name' is in all objects # } ``` -------------------------------- ### GenSON Python API: Exporting Schema Source: https://github.com/wolverdude/genson/blob/master/README.rst Shows how to export the generated JSON schema from a SchemaBuilder object as a Python dictionary. This method serializes the inferred schema structure. ```python # Export the schema as a Python dict. builder.to_schema() {"$schema": "http://json-schema.org/schema#", "type": "object", "properties": { "hi": {"type": ["integer", "string"]}}, "required": ["hi"]} ``` -------------------------------- ### Python - SchemaBuilder with Extra Strategies Source: https://github.com/wolverdude/genson/blob/master/README.rst Extends the base SchemaBuilder to include custom strategies without replacing existing ones. The EXTRA_STRATEGIES class constant is used to add new strategies, which have higher priority than default strategies. ```python # new SchemaBuilder class that uses the MinNumber strategy in addition # to the existing strategies. Both MinNumber and Number are active, but # MinNumber has priority, so it effectively replaces Number. class MinNumberSchemaBuilder(SchemaBuilder): """ all number nodes include minimum """ EXTRA_STRATEGIES = (MinNumber,) ``` -------------------------------- ### Generate Schema with Pattern Properties Source: https://context7.com/wolverdude/genson/llms.txt Explains how to generate JSON Schema that includes 'patternProperties' for keys matching a regular expression. This is useful for objects with dynamically named keys, like those containing numeric strings. ```python from genson import SchemaBuilder import re # Use seed schema to enable patternProperties builder = SchemaBuilder() builder.add_schema({ 'type': 'object', 'patternProperties': {r'^\d+$': None} }) # Add objects with numeric string keys builder.add_object({'1': 100, '2': 200, '3': 300}) builder.add_object({'10': 1000, '20': 2000}) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'object', # 'patternProperties': { # '^\d+$': {'type': 'integer'} # } # } ``` -------------------------------- ### Generate JSON Schema from Multi-Object File with Custom Delimiter Source: https://context7.com/wolverdude/genson/llms.txt This command generates a JSON Schema from a file containing multiple JSON objects separated by a custom delimiter ('---'). The '-i 2' option likely specifies the indentation level for the output schema. ```bash genson multi-object-file.json -d "---" -i 2 ``` -------------------------------- ### Generate Array Schema (List Mode) Source: https://context7.com/wolverdude/genson/llms.txt Shows how GenSON generates a schema for arrays where all elements are expected to conform to a single schema. This is the default behavior when adding array objects. ```python from genson import SchemaBuilder # Default list mode - all items share one schema builder = SchemaBuilder() builder.add_object([1, 2, 3, 4, 5]) builder.add_object([10, 20, 30]) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'array', # 'items': {'type': 'integer'} # } # Mixed types in array builder2 = SchemaBuilder() builder2.add_object([1, "two", 3.0, True]) schema2 = builder2.to_schema() print(schema2) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'array', # 'items': {'type': ['boolean', 'integer', 'number', 'string']} # } ``` -------------------------------- ### Python - SchemaBuilder with Exclusive Strategies Source: https://github.com/wolverdude/genson/blob/master/README.rst Extends the base SchemaBuilder to completely replace the default strategies with a custom set. The STRATEGIES class constant is used for this purpose, making the builder handle only the specified strategies. ```python # this class *ONLY* has the MinNumber strategy. Any object that is not # a number will cause an error. class ExclusiveMinNumberSchemaBuilder(SchemaBuilder): """ all number nodes include minimum, and only handles number """ STRATEGIES = (MinNumber,) ``` -------------------------------- ### Generate JSON Schema without Schema URI Keyword using GenSON Source: https://context7.com/wolverdude/genson/llms.txt This command generates a JSON Schema from 'data.json' but explicitly sets the schema URI keyword to NULL, effectively omitting it from the generated schema. ```bash genson data.json -$ NULL ``` -------------------------------- ### Generate Array List Validation Schema with Genson Source: https://github.com/wolverdude/genson/blob/master/README.rst This Python code demonstrates the default behavior of Genson when adding an array object, which is to generate a schema for list validation. The `items` keyword specifies a union of types for all elements in the array. ```python from genson import SchemaBuilder builder = SchemaBuilder() builder.add_object(['one', 1]) builder.to_schema() ``` -------------------------------- ### Generate Nested Object JSON Schema with Genson Python Source: https://context7.com/wolverdude/genson/llms.txt Demonstrates how to use Genson's SchemaBuilder to generate a JSON schema from a nested Python dictionary. The builder processes the object and outputs a schema reflecting its structure, types, and required fields. This is useful for validating JSON data with complex, nested structures. ```python from genson import SchemaBuilder builder = SchemaBuilder() builder.add_object({ "user": { "profile": { "name": "Alice", "age": 30 }, "posts": [ {"title": "Hello", "views": 100}, {"title": "World", "views": 200} ] } }) schema = builder.to_schema() print(schema) # Output: # { # '$schema': 'http://json-schema.org/schema#', # 'type': 'object', # 'properties': { # 'user': { # 'type': 'object', # 'properties': { # 'profile': { # 'type': 'object', # 'properties': { # 'name': {'type': 'string'}, # 'age': {'type': 'integer'} # }, # 'required': ['name', 'age'] # }, # 'posts': { # 'type': 'array', # 'items': { # 'type': 'object', # 'properties': { # 'title': {'type': 'string'}, # 'views': {'type': 'integer'} # }, # 'required': ['title', 'views'] # } # } # }, # 'required': ['profile', 'posts'] # } # }, # 'required': ['user'] # } ``` -------------------------------- ### Control JSON Schema URI with Genson Python Source: https://context7.com/wolverdude/genson/llms.txt Shows how to control the '$schema' URI in generated JSON schemas using Genson. You can use the default URI, specify a custom one (e.g., for Draft 7), or omit it entirely by setting `schema_uri` to `None` during SchemaBuilder initialization. This allows compatibility with different JSON schema validators. ```python from genson import SchemaBuilder # Default schema URI builder = SchemaBuilder() builder.add_object({"id": 1}) json_output = builder.to_json(indent=2) print(json_output) # Output: # { # "$schema": "http://json-schema.org/schema#", # "type": "object", # "properties": { # "id": { # "type": "integer" # } # }, # "required": [ # "id" # ] # } # Custom schema URI builder2 = SchemaBuilder(schema_uri='http://json-schema.org/draft-07/schema#') builder2.add_object({"id": 1}) schema2 = builder2.to_schema() print(schema2['$schema']) # Output: 'http://json-schema.org/draft-07/schema#' # No schema URI builder3 = SchemaBuilder(schema_uri=None) builder3.add_object({"id": 1}) schema3 = builder3.to_schema() print('$schema' in schema3) # Output: False ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.