Saravanan666/pypi-org huggingface dataset:
Package: json-schema-to-class
json-schema-to-classConvert JSON Schema into Python ClassInstallationNeed Python 3.6+.pipinstalljson-schema-to-classUsageFor example, converttests/test_schema.jsoninto Python class:# generate & highlightjson-schema-to-classtests/test_schema.json--indent2|pygmentize# or generate to filejson-schema-to-classtests/test_schema.json-otests/schema_build.py# generate code with __repr__ methodjson-schema-to-classtests/test_schema.json--indent2--repr|pygmentizeGettests/schema_build.pyas follow:fromtypingimportListclassWarmUp:def__init__(self,values:dict=None):values=valuesifvaluesisnotNoneelse{}self.start:float=values.get("start",0.0)self.steps:int=values.get("steps",0)classLrSchedulerConfig:def__init__(self,values:dict=None):values=valuesifvaluesisnotNoneelse{}self.lr_mode:str=values.get("lr_mode",'cos')self.base_lr:float=values.get("base_lr",None)self.target_lr:float=values.get("target_lr",0.0002)self.decay_factor:float=values.get("decay_factor",0.1)self.milestones:List[float]=values.get("milestones",[0.3,0.6,0.9])self.lr_decay:float=values.get("lr_decay",0.98)self.warm_up=WarmUp(values=values.get("warm_up"))classLrSchedulerConfigs(list):def__init__(self,values:list=None):super().__init__()values=valuesifvaluesisnotNoneelse[]self[:]=[LrSchedulerConfig(value)forvalueinvalues]
Package: jsonschematomappings
jsonschematomappingsConvert JSON schema to OpenSearch/ElasticSearch mappingsInstallFrom pypi:pip install jsonschematomappingsFrom repository directory:pip install -e .If developing/running tests:pip install -r requirements/requirements-test.txtRun$ jsonschematomappings -h
usage: jsonschematomappings [-h] [--template TEMPLATE] json_schema

Convert a JSON schema document to an OpenSearch/ElasticSearch mappings document

positional arguments:
  json_schema          JSON schema document

optional arguments:
  -h, --help           show this help message and exit
  --template TEMPLATE  Template mappings document
Package: json-schema-tool
JSON Schema ToolJSON Schema Tool is a python implementation of JSON Schema, draft 2020-12.
It offers various additional features commonly not found in other librariesObviously, the core of JSON Schema Tool is the validation of JSON documents.
This can be done as follows:fromjson_schema_toolimportparse_schemaschema={'$schema':'https://json-schema.org/draft/2020-12/schema','type':'object','properties':{'foo':{'type':'string'}}}validator=parse_schema(schema)result=validator.validate({"foo":"bar"})# result.ok == Trueresult=validator.validate("invalid")# result.ok == FalseInstallationYou can install JSON Schema Tool via pip:python-mpipinstalljson_schema_toolSchema Coverage MeasurementYou can use coverage to assess the completeness of your test data.
Schema coverage works on the keyword level, i.e., JsonSchema Tool checks, how many constraints have been actually checked during instance validation:fromjson_schema_toolimportcoverage,parse_schemaschema={'$schema':'https://json-schema.org/draft/2020-12/schema','type':'object','properties':{'foo':{'type':'string'}}}validator=parse_schema(schema)cov=coverage.SchemaCoverage(validator)result=validator.validate({})cov.update(result)print(cov.coverage())# 0.3result=validator.validate({"foo":"bar"})cov.update(result)print(cov.coverage())# 1.0withopen("schema-coverage.html","w")asf:cov.render_coverage(f)Type InferenceGiven a validator, you can use it to query the types of the schema.
This even works for complex and composed schemas:fromjson_schema_toolimportparse_schemaschema={'$schema':'https://json-schema.org/draft/2020-12/schema','anyOf':[{"type":"object"},{"const":"foo"}]}validator=parse_schema(schema)print(validator.get_types())# {'object', 'string'}Validation PerformanceYou can drastically increase validation performance by using short circuit evaluation (SCE).
By using SCE, evaluation terminates as soon as the first error in the JSON instance is found.
For example, an allOf does not visit all sub schemas, if the first sub-schema already fails.
You can activate SCE as follows:fromjson_schema_toolimportschema# use parse_schema to build your validator...config=schema.ValidationConfig(short_circuit_evaluation=True)result=validator.validate({"foo":"bar"},config)Please note, that SCE does not work together with coverage measurement.
Package: jsonschematools
jsonschematoolsDescriptionjsonschematoolsis a Python library that provides utilities for working with JSON Schema. It includes features for adding and updating enums in the$defssection of a JSON schema, and updating a property of a JSON schema with an existing enum reference.InstallationTo installjsonschematools, you can use pip:pipinstalljsonschematoolsUsageHere is a basic example of how to usejsonschematools:fromjsonschematools.enumsimportadd_or_update_enum_in_defs,update_property_with_enum# Define a basic schemaschema={"type":"object","properties":{"name":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}},},"$defs":{},}# Add a new enum to the schemaschema=add_or_update_enum_in_defs(schema,"Colors",["Red","Blue","Green"])# schema now looks like this:# {#   "type": "object",#   "properties": {#     "name": {#       "type": "string"#     },#     "tags": {#       "type": "array",#       "items": {#         "type": "string"#       }#     }#   },#   "$defs": {#     "Colors": {#       "type": "string",#       "enum": [#         "Red",#         "Blue",#         "Green"#       ]#     }#   }# }# Update a property with the new enumschema=update_property_with_enum(schema,"Colors","tags")# schema now looks like this:# {#   "type": "object",#   "properties": {#     "name": {#       "type": "string"#     },#     "tags": {#       "type": "array",#       "items": {#         "$ref": "#/$defs/Colors"#       }#     }#   },#   "$defs": {#     "Colors": {#       "type": "string",#       "enum": [#         "Red",#         "Blue",#         "Green"#       ]#     }#   }# }TestingTests are written using pytest. To run the tests, use the following command:pytestContributingContributions are welcome! Please fork the repository and create a pull request with your changes.Licensejsonschematoolsis licensed under the MIT License.ContactFor any questions or concerns, please open an issue on GitHub.
Package: jsonschema-to-openapi
jsonschema-to-openapiConverts a JSON schema to an OpenAPI specification version 3.0.Installationpip install jsonschema-to-openapiUsageCLIjsonschema-to-openapimy_json_schema.jsonmy_open_api_spec.jsonPackage>>>fromjsonschema_to_openapi.convertimportconvert>>>schema={}# Your json schema as dictionary.>>>convert(schema){}# Your OpenAPI specification as dictionary.Caveats and LimitationsIf you have acomplex schema, where you extend a base schema with the$refoperator, you will need to put all base schemas under a "definitions" key in root.Abitrarily nestedxOfs cannot be resolved yet. The program won't fail and will procude valid OpenAPI specification, but the result will still contain nestedxOfoperators.Input:{"anyOf":[{"$ref":"#/definitions/my_object"},{"anyOf":[{"type":"null"}]}],"definitions":{"my_object":{"type":"string"}}}Output:{"anyOf":[{"$ref":"#/definitions/my_object"},{"anyOf":[{"type":"null"}]}],"definitions":{"my_object":{"nullable":false,"type":"string"}}}ChangelogPlease take a look at theCHANGELOG.mdfor notable changes to jsonschema-to-openapi.LicenseSee theLICENSEfor details.DevelopmentWe welcome new contributions to this project!Source CodeYou can check the latest source code with the command:git clone git@gitlab.com:InstaffoOpenSource/DataScience/jsonschema-to-openapi.gitLintingAfter cloning and installing the dependencies, you can lint the project by executing:make lintTestingAfter cloning and installing the dependencies, you can test the project by executing:make testHelp and SupportAuthorsJan-Benedikt Jaguschjan@instaffo.deAcknowledgementsThis project started as a Python port ofjson-schema-to-openapi-schema.
Package: jsonschema-to-typeddict
jsonschema-to-typeddictprecommit hook for creating a TypedDict definition for your JsonSchemaUsageAdd the following to your.pre-commit-config.yaml:-repo:https://github.com/henriquegemignani/jsonschema-to-typeddictrev:v1.0hooks:-id:jsonschema-to-typeddictfiles:src/my_package/files/schema.jsonargs:[--output-path,src/my_package/configuration.pyi,--root-name,Configuration]
Package: jsonschema-typed
JSON Schema-powered type annotationsThis package provides a way to automatically produce type annotations based
onjsonschema-schemas.Not all concepts covered byjsonschemaare expressible within Python typing annotations. However, most things
will work like you'd expect. Most types are translated trivially
(integer,number,string,array,booleanandnull).
The interesting type isobject, which is translated into aTypedDict.Warning:This is based on themypy plugin system, which
is stated to have no backwards compatibility guarantee. New versions of mypy might not be supported immediately.ExampleA JSON schema:{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://foo.qwerty/some/schema#","title":"Foo Schema","type":"object","properties":{"title":{"type":"string"},"awesome":{"type":"number"}},"required":["title"]}A TypedDict:fromtypingimportTYPE_CHECKINGfromjsonschema_typedimportJSONSchemadata:JSONSchema["path/to/schema.json"]={"title":"baz"}ifTYPE_CHECKING:reveal_type(data)# Revealed type is 'TypedDict('FooSchema', {'title': builtins.str,#                                           'awesome'?: Union[builtins.int, builtins.float]})'data["description"]="there is no description"# TypedDict "FooSchema" has no key 'description'data["awesome"]=42data["awesome"]=None# Argument 2 has incompatible type "None"; expected "Union[int, float]"You can also get types of parts of a schema, as well as types of elements in arrays. Take a look at thetest casesfor more examples of usage.Installationpipinstalljsonschema-typedYou also need to enable the plugin(s) in yourmypy.iniconfiguration file:# mypy.ini[mypy]plugins=jsonschema_typed.plugin,jsonschema_typed.optional_typed_dict# Due to a quirk of how these type hints are generated, mypy's caching breaks.# Disabling caching might be required.cache_dir=/dev/nullRequirementsThe above installations resolves the dependencies, which consist ofmypyandjsonschema(naturally).
Testing has been done with versions:mypy==0.761jsonschema==3.2.0Probably some older versions will also work. Report anissueif you need other versions.LimitationsadditionalPropertiesdoesn't really have an equivalent in TypedDict.Thedefaultkeyword is not supported; but see:https://github.com/python/mypy/issues/6131.Self-references (e.g."#") can't really work properly until nested
forward-references are supported; see:https://github.com/python/mypy/issues/731.
Package: jsonschema-typed-v2
JSON Schema-powered type annotationsThis package provides a way to automatically produce type annotations based
onjsonschema-schemas.Not all concepts covered byjsonschemaare expressible within Python typing annotations. However, most things
will work like you'd expect. Most types are translated trivially
(integer,number,string,array,booleanandnull).
The interesting type isobject, which is translated into aTypedDict.Warning:This is based on themypy plugin system, which
is stated to have no backwards compatibility guarantee. New versions of mypy might not be supported immediately.Note: This is a maintained fork oferickpeirson's original start
on this project. The original repo seems to be abandoned and its current state is not functional.Make sure to install
the right package from PyPI,jsonschema-typed-v2ExampleA JSON schema:{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://foo.qwerty/some/schema#","title":"Foo Schema","type":"object","properties":{"title":{"type":"string"},"awesome":{"type":"number"}},"required":["title"]}A TypedDict:fromtypingimportTYPE_CHECKINGfromjsonschema_typedimportJSONSchemadata:JSONSchema["path/to/schema.json"]={"title":"baz"}ifTYPE_CHECKING:reveal_type(data)# Revealed type is 'TypedDict('FooSchema', {'title': builtins.str,#                                           'awesome'?: Union[builtins.int, builtins.float]})'data["description"]="there is no description"# TypedDict "FooSchema" has no key 'description'data["awesome"]=42data["awesome"]=None# Argument 2 has incompatible type "None"; expected "Union[int, float]"You can also get types of parts of a schema, as well as types of elements in arrays. Take a look at thetest casesfor more examples of usage.Installationpipinstalljsonschema-typed-v2You also need to enable the plugin(s) in yourmypy.iniconfiguration file:# mypy.ini[mypy]plugins=jsonschema_typed.plugin,jsonschema_typed.optional_typed_dict# Due to a quirk of how these type hints are generated, mypy's caching breaks.# Disabling caching might be required.cache_dir=/dev/nullRequirementsThe above installations resolves the dependencies, which consist ofmypyandjsonschema(naturally).
Testing has been done with versions:mypy==0.761jsonschema==3.2.0Probably some older versions will also work. Report anissueif you need other versions.LimitationsadditionalPropertiesdoesn't really have an equivalent in TypedDict.Thedefaultkeyword is not supported; but see:https://github.com/python/mypy/issues/6131.Self-references (e.g."#") can't really work properly until nested
forward-references are supported; see:https://github.com/python/mypy/issues/731.
Package: jsonschema-validator-new
JSON Schema validatorTools to generate Python types based on TypedDict from a JSON schemaQuick startinstall:python3-mpipinstall--userjsonschema-validatorConvert a JSON schema to a Python file contains the types:jsonschema-validator--helpDefaultThe default values are exported in the Python file, then you can do something like that:value_with_default=my_object.get('field_name',my_schema.FIELD_DEFAULT)ValidationThis package also provide some validations features for YAML file based onjsonschema.Additional features:Obtain the line and columns number in the errors, if the file is loaded withruamel.yaml.Export the default provided in the JSON schema.importruamel.yamlimportpkgutilimportjsonschema_validatorschema_data=pkgutil.get_data("<package>","schema.json")withopen(filename)asdata_file:yaml=ruamel.yaml.YAML()# type: ignoredata=yaml.load(data_file)errors,data=jsonschema_validator.validate(filename,data,schema)iferrors:print("\n".join(errors))sys.exit(1)Pre-commit hooksThis project provides pre-commit hooks to automatically generate the files.repos:-repo:https://github.com/camptocamp/jsonschema-validatorrev:<version># Use the ref you want to point athools:-id:jsonschema-validatorfiles:|(?x)^(...)$ContributingInstall the pre-commit hooks:pipinstallpre-commit
pre-commitinstall--allow-missing-configTheprospectortests should pass.The code should be typed.The code should be tested withpytests.
Package: json-scribe
Write your logs as json-lines.Source Codeaweber/json-scribeDownloadsjson-scribe @pypi.orgThis library is the result of sending docker container logs to loggly.
Loggly works well with structured Syslog data but if you pass structured
Syslog lines to an aggregator as JSON you end up with an unindexed mess.
This library includes a few classes that make it easier and cleaner to send
log content as JSON objects on single linesincluding exceptions.UsageConfiguration{"version":1,"filters":{"defaultsetter":{"()":"jsonscribe.AttributeSetter","add_fields":{"correlation_id":"ext://UUID"}}},"formatters":{"jsonlines":{"()":"jsonscribe.JSONFormatter","include_fields":["name","levelname","asctime","message","module","correlation_id","exc_info"],}},"handlers":{"loggly":{"class":"logging.StreamHandler","formatter":"jsonlines","filters":["defaultsetter"],"stream":"ext://sys.stdout"}},"loggers":{"somepackage":{"level":"DEBUG",}},"root":{"level":"INFO","handlers":["jsonlines"]}}LoggingThe following snippet is the simplest usage.  It is nothing more than the
textbook usage of the logging module.  It uses the logging configuration from
above and generates a JSON blob.importlogging.configimportjsonif__name__=='__main__':config=json.load(open('config.json'))logging.config.dictConfig(config)logger=logging.getLogger(__package__).getChild('main')logger.info('processing request')The JSON message looks something like the following.  It is reformatted to
make it readable.  The default is to render it as compact JSON.{"name":"somepackage.main","levelname":"INFO","asctime":"2018-08-09T07:44:54.231","module":"somepackage.entrypoints","correlation_id":"33CA3FB3-D66F-4D32-83A5-D5A8C3D92A6E","message":"processing request","exc_info":null}
Package: jsonsearch
JsonSearchJsonSearch is a simple, yet effcient python library for searhing specific elements in json data.>>> from jsonsearch import JsonSearch
>>> test_data = {
...     "store": {
...         "book": [
...             {
...                 "category": "reference",
...                 "author": "Nigel Rees",
...                 "title": "Sayings of the Century",
...                 "price": 8.95
...             },
...             {
...                 "category": "fiction",
...                 "author": "Evelyn Waugh",
...                 "title": "Sword of Honour",
...                 "price": 12.99
...             },
...             {
...                 "category": "fiction",
...                 "author": "Herman Melville",
...                 "title": "Moby Dick",
...                 "isbn": "0-553-21311-3",
...                 "price": 8.99
...             },
...             {
...                 "category": "fiction",
...                 "author": "J. R. R. Tolkien",
...                 "title": "The Lord of the Rings",
...                 "isbn": "0-395-19395-8",
...                 "price": 22.99
...             }
...         ],
...         "bicycle": {
...             "color": "red",
...             "price": 19.95
...         }
...     },
...     "expensive": 10
... }
>>> jsondata = JsonSearch(object=test_data, mode='j')
>>> jsondata.search_all_value(key='title')               
['Sayings of the Century', 'Sword of Honour', 'Moby Dick', 'The Lord of the Rings']
>>> jsondata.search_all_path(key='title')       
[['store', 'book', 0, 'title'], ['store', 'book', 1, 'title'], ['store', 'book', 2, 'title'], ['store', 'book', 3, 'title']]
>>> jsondata.search_first_value(key='title')           
'Sayings of the Century'
>>> jsondata.search_first_path(key='title')      
['store', 'book', 0, 'title']When json data have nested objects, JsonSearch allows you to find specific elements in json data easily.Take the program above as an example, if you want to get the first'title'value in data, you don't need to usetest_data['store']['book'][0]['title']anymore, you can just usejsondata.search_first_value(key='title').InstallJsonSearch is available on PyPI:pip install jsonsearchorpip install --index-url https://pypi.org/simple/ jsonsearch
Package: json-secret-diary
Secret DiaryMy own project to manage my daily diary, works with onlyPython 3How it worksThe entire diary is based only on JSON text, everything is done with JSON.
Diary has 'public' infos and 'secret' infos, the secret part is encrypted with AES algorithm.The public part is called 'summary', this will be usefull to help you to know what that page of diary talk about or specific infos.No connection to internet required, new diary will be created if username is not recognized (obviously with a prompt to allow or deny).Once you wrote you can't edit text (both public and private) but you can write without limits.Password of your diary is stored in the same JSON file, the name is yout username setted at first start.How to installThis code can be installed withpip, if you have pip installed execute the pip command to install new packagepip install json_secret_diaryExample of usageYou have 2 ways to use my package from command-line, simply writejson_secret_diaryand creation start!You can also use with your python project, here an example:importjson_secret_diarymy_username='example'my_password='example_pw'# Create Diary objectmy_diary=json_secret_diary.Diary(my_username,my_password)# Access to diary, if exist# if not exist create new one if authorizedmy_diary.access()
Package: jsonselect
#jsonselect.py<img src="https://travis-ci.org/mwhooker/jsonselect.png" />jsonselect.py is a python implementation of https://github.com/fd/json_selectYou can find more information here http://jsonselect.org/## Usagejsonselect can be called directly from the command line.`python -m jsonselect <selector> < jsonfile`This is usefull, for example, for parsing out values from JSON APIs.```sh$aws ec2 describe-instances --filters "Name=tag:Name,Values=kafka" | python -m jsonselect .InstanceId["i-12345678", "i-23456789", "i-3456789A"]```### Full Usage```usage: __main__.py [-h] [--list | --machine-readable] selector [infile]parse json with jsonselect.positional arguments:selectorinfileoptional arguments:-h, --help          show this help message and exit--list, -l          new-line separated list of values. works best on lists.--machine-readable  Print json with no formatting```## Project statusjsonselect.py currently implements levels 1 & 2 of these conformance tests https://github.com/lloyd/JSONSelectTestslevel 3 is unimplemented because I was having trouble understanding what the correct behavior should be##Testsget the upstream conformance tests:git submodule update --initRun specific level conformance tests withnosetests -m '.*_level_1' ./tests/test_conformance.py
Package: json-sempai
Have you ever been kept awake at night, desperately feeling a burning desire to
do nothing else but directly import JSON files as if they were python modules[1]? Now you can!This abomination allows you to writeimportsome_json_fileand ifsome_json_file.jsoncan be found, it will be available as if it is a
python module.UsageSlap a json file somewhere on your python path.tester.json:{"hello":"world","this":{"can":{"be":"nested"}}}Now import jsonsempai and your json file!>>>fromjsonsempaiimportmagic>>>importtester>>>tester<module'tester'from'tester.json'>>>>tester.hellou'world'>>>tester.this.can.beu'nested'>>>Alternatively, a context manager may be used (100% less magic):>>>importjsonsempai>>>withjsonsempai.imports():...importtester>>>tester<module'tester'from'tester.json'>Python packages are also supported:$tree.└──python_package├──file.json├──__init__.py└──nested_package├──__init__.py└──second.json>>>fromjsonsempaiimportmagic>>>frompython_packageimportfile>>>file<module'python_package.file'from'python_package/file.json'>>>>importpython_package.nested_package.second>>>python_package.nested_package.second<module'python_package.nested_package.second'from'python_package/nested_package/second.json'>InstallingInstall from pip:$pipinstalljson-sempaior clone this repo and install from source:$pythonsetup.pyinstallTo purge this horror from your machine:$pipuninstalljson-sempai[1]Disclaimer: Only do this if you hate yourself and the rest of the world.