def schema_from_json(json_body): try: j = json.loads(json_body) s = genson.SchemaBuilder(schema_uri=None) s.add_object(j) return {'schema': s.to_schema()} except JSONDecodeError: return {}
def schema_from_json(json_body, remove_required=False): try: j = json.loads(json_body) s = genson.SchemaBuilder(schema_uri=None) s.add_object(j) schema = s.to_schema() if remove_required: __delete_nested_keys(schema, ["required"]) return {"schema": schema} except JSONDecodeError: return {}
def urls_to_json_schema(urls): builder = genson.SchemaBuilder() builder.add_schema({"type": "object", "properties": {}}) for url in urls: response = requests.get(url) if response.status_code == 200: builder.add_object(JSonCleaning.clean_keys(response.json())) else: print("Error {} while fetching url {}".format( response.status_code, url)) builder.to_schema() schema = builder.to_json(indent=4) return json.loads(schema)
def test_response_schema(self, json, description="json数据模式正确"): builder = genson.SchemaBuilder() builder.add_object(json) schema = builder.to_schema() self._script += (""" pm.test('%s', function() { var result=tv4.validateResult(JSON.parse(responseBody), %s); if(!result.valid){ console.log(result); } pm.expect(result.valid).to.be.true; }); """ % (description, schema))
def generate_schema_from_data( raw_data, data_source='', ): """generate jsonschema from raw dict with genson. Broken out as test-helper Args: raw_data (dict): raw json data from source data_source (str): source of data being jsonschema'd Returns: dict: jsonschema """ builder = genson.SchemaBuilder(data_source) builder.add_object(raw_data) return builder.to_schema()
def _generate_schema_from_example_and_description(input, description): ''' With an example input, a schema is automatically generated that conforms to the example in json-schema.org. The description given by the users is then added to the schema. ''' s = genson.SchemaBuilder(None) s.add_object(input) input_schema = s.to_schema() if description is not None: if 'properties' in input_schema: # Case for input = {'x':1}, input_description='not a dict' if not isinstance(description, dict): msg = f'{input} and {description} do not match' logger.error(msg) raise Exception(msg) for key in description: # Case for input = {'x':1}, # input_description={'x':'x value', 'y':'y value'} if key not in input_schema['properties']: msg = f'{key} not found in {input}' logger.error(msg) raise Exception(msg) else: input_schema['properties'][key][ 'description'] = description[key] else: if isinstance(description, dict): raise Exception(f'{input} and {description} do not match') else: input_schema['description'] = description try: # This should not fail unless there are bugs with either genson or # jsonschema. jsonschema.validate(input, input_schema) except Exception as e: logger.error(f'Internal error validating schema: {str(e)}') raise return input_schema
import json import genson import json_schema_descriptions as jsd current_schema = None output_file = "output.json" new_schema = "new_odmts_schema.json" with open(output_file) as file: output = json.load(file) builder = genson.SchemaBuilder() # Start with current schema if current_schema != None: with open(current_schema) as file: builder.add_schema(json.load(file)) # Include patterns and null types that may not be detected directly builder.add_schema({ 'properties': { 'parameters': {}, 'design': { 'properties': { 'hubs': { 'patternProperties': { r'^.*$': {} } }, 'legs': { 'patternProperties': {
from pprint import pformat, pprint import xmltodict import genson fn = "xml_example1.xml" with open(fn) as fh: xd = xmltodict.parse(fh.read()) print(pformat(xd)) print(pformat(xd['catalog']['book'])) fan_books = [ x['title'] for x in xd['catalog']['book'] if x['genre'] == "Fantasy" ] print(" {} {}".format(len(fan_books), fan_books)) sb = genson.SchemaBuilder() sb.add_object(xd) print(sb.to_json(indent=2))