Saravanan666/pypi-org huggingface dataset:
Package: jsonrpc-requests
This is a compact and simple JSON-RPC client implementation written while debugging a picky server.Main FeaturesPython 2.7, 3.4, 3.5, 3.6 compatibleExposes requests optionsSupports nested namespaces (eg.app.users.getUsers())100% test coverageTODOBatch requests (http://www.jsonrpc.org/specification#batch)Usagefromjsonrpc_requestsimportServerserver=Server('http://localhost:8080')server.foo(1,2)server.foo(bar=1,baz=2)server.foo({'foo':'bar'})server.foo.bar(baz=1,qux=2)A notification:fromjsonrpc_requestsimportServerserver.foo(bar=1,_notification=True)Pass through arguments to requests (see alsorequests  documentation)fromjsonrpc_requestsimportServerserver=Server('http://localhost:8080',auth=('user','pass'),headers={'x-test2':'true'})Pass through requests exceptionsfromjsonrpc_requestsimportServer,TransportErrorserver=Server('http://unknown-host')try:server.foo()exceptTransportErrorastransport_error:print(transport_error.cause)# this will hold a `requests.exceptions.RequestException` instanceTestsInstall the Python tox package and runtox, it’ll test this package with various versions of Python.Credits@mbroadstfor providing full support for nested method calls, JSON-RPC RFC
compliance and other improvements.@vaabfor providing api and tests improvements, better RFC compliance.
Package: jsonrpcserver
Process incoming JSON-RPC requests in Python.fromjsonrpcserverimportmethod,serve,Success@methoddefping():returnSuccess("pong")if__name__=="__main__":serve()Or usedispatchinstead ofserve:response=dispatch('{"jsonrpc": "2.0", "method": "ping", "id": 1}')# => '{"jsonrpc": "2.0", "result": "pong", "id": 1}'Watch a video on how to use it.Full documentation is atjsonrpcserver.com.See also:jsonrpcclient
Package: jsonrpc_tornado
jsonrpc_tornado: a compact asynchronous JSON-RPC client library for `Tornado framework <http://www.tornadoweb.org/>`_=======================================================================================================Main Features-------------* Python 2.7 & 3.4 compatible* Exposes tornado.httpclient options* Non-Blocking I/O* Supports nested namespaces (eg. `app.users.getUsers()`)Install-------pip install git+https://github.com/artemmus/jsonrpc_tornado.gitUsage-----A synchronous example:.. code-block:: pythonfrom jsonrpc_tornado import JSONRPCServerfrom tornado.httpclient import HTTPClientdef fetch(server_url):server = JSONRPCServer(server_url, http_client=HTTPClient,request_timeout=5.0)# call some function on the serverresult = server.foo(1, 2)An example of non-blocking calls:.. code-block:: pythonfrom jsonrpc_tornado import JSONRPCServer, ProtocolError, TransportErrorfrom tornado import gen@gen.coroutinedef fetch_coroutine(server_url):server = JSONRPCServer(server_url, request_timeout=5.0)try:# call some function on the serverresult = yield server.foo(1, 2)except ProtocolError as err:logging.error('Some RPC error %s, %s', err.code, err)except TransportError as err:# err.args[1] refers to appropriate HTTPErrorlogging.error('Transport error %s', err.args[1])TODO----* TestsCredits-------Based on `jsonrpc_requests <http://github.com/gciotta/jsonrpc-requests>` by `Giuseppe Ciotta <gciotta@gmail.com>`_.
Package: jsonrpyc
Minimal python RPC implementation based on theJSON-RPC 2.0 specs.Original source hosted atGitHub.Usagejsonrpyc.RPCinstances basically wrap an input stream and an output stream in order to communicate with otherservices.
A service is not even forced to be written in Python as long as it strictly implements the JSON-RPC 2.0 specs.
A suitable implementation for NodeJs isnode-json-rpc.
Ajsonrpyc.RPCinstance may wrap atargetobject.
Incomming requests will be routed to methods of this object whose result might be sent back as a response. Example implementation:server.pyimportjsonrpycclassMyTarget(object):defgreet(self:MyTarget,name:str)->str:returnf"Hi,{name}!"jsonrpyc.RPC(MyTarget())client.pyimportjsonrpycfromsubprocessimportPopen,PIPEp=Popen(["python","server.py"],stdin=PIPE,stdout=PIPE)rpc=jsonrpyc.RPC(stdout=p.stdin,stdin=p.stdout)## sync usage#print(rpc("greet",args=("John",),block=0.1))# => "Hi, John!"## async usage#defcb(err:Exception|None,res:str|None=None)->None:iferr:raiseerrprint(f"callback got:{res}")rpc("greet",args=("John",),callback=cb)# cb is called asynchronously which prints# => "callback got: Hi, John!"## shutdown#p.stdin.close()p.stdout.close()p.terminate()p.wait()InstallationInstall simply viapip.pipinstalljsonrpycContributingIf you like to contribute to jsonrpyc, I'm happy to receive pull requests.
Just make sure to add new test cases and run them via:>pytesttestsDevelopmentSource hosted atGitHubReport issues, questions, feature requests onGitHub Issues
Package: jsonschema
jsonschemais an implementation of theJSON Schemaspecification for Python.>>>fromjsonschemaimportvalidate>>># A sample schema, like what we'd get from json.load()>>>schema={..."type":"object",..."properties":{..."price":{"type":"number"},..."name":{"type":"string"},...},...}>>># If no exception is raised by validate(), the instance is valid.>>>validate(instance={"name":"Eggs","price":34.99},schema=schema)>>>validate(...instance={"name":"Eggs","price":"Invalid"},schema=schema,...)# doctest: +IGNORE_EXCEPTION_DETAILTraceback(mostrecentcalllast):...ValidationError:'Invalid'isnotoftype'number'It can also be used from the command line by installingcheck-jsonschema.FeaturesFull support forDraft 2020-12,Draft 2019-09,Draft 7,Draft 6,Draft 4andDraft 3Lazy validationthat can iteratively reportallvalidation errors.Programmatic queryingof which properties or items failed validation.Installationjsonschemais available onPyPI. You can install usingpip:$pipinstalljsonschemaExtrasTwo extras are available when installing the package, both currently related toformatvalidation:formatformat-nongplThey can be used when installing in order to include additional dependencies, e.g.:$pipinstalljsonschema'[format]'Be aware that the mere presence of these dependencies – or even the specification offormatchecks in a schema – donotactivate format checks (as per the specification).
Please read theformat validation documentationfor further details.AboutI’m Julian Berman.jsonschemais onGitHub.Get in touch, via GitHub or otherwise, if you’ve got something to contribute, it’d be most welcome!You can also generally find me on Libera (nick:Julian) in various channels, including#python.If you feel overwhelmingly grateful, you can alsosponsor me.And for companies who appreciatejsonschemaand its continued support and growth,jsonschemais also now supportable viaTideLift.Release Informationv4.21.1Slightly speed up thecontainskeyword by removing some unnecessary validator (re-)creation.
Package: json_schema
json_schemais a JSON-based schema validation package.JSON-based means that its feature-set is adjusted to JSON, but it doesn’t
require JSON data: any Python objects are fine, as long as they’re of the
primary Python types.Let’s start off with an example:from json_schema import Schema, AnyInteger

my_schema = Schema([u"set-temp", {u"degrees": AnyInteger}])

if my_schema.validate([u"set-temp", {u"degrees": 10}]):
    print "Valid!"It’s a very declarative way of saying how your schema looks. With the architechture
thatjson_schemais built on, you can customize pretty much anything.
Package: jsonschema2md
jsonschema2mdConvert JSON Schemas to simple, human-readable Markdown documentation.For example:{"$id":"https://example.com/person.schema.json","$schema":"http://json-schema.org/draft-07/schema#","title":"Person","description":"JSON Schema for a person object.","type":"object","properties":{"firstName":{"type":"string","description":"The person's first name."},"lastName":{"type":"string","description":"The person's last name."}}}will be converted to:PersonJSON Schema for a person object.PropertiesfirstName(string): The person's first name.lastName(string): The person's last name.See theexamplesdirectory for more elaborate examples.InstallationInstall with pippipinstalljsonschema2mdUsageFrom the CLIjsonschema2md[OPTIONS]<input.json><output.md>From Pythonimportjsonimportjsonschema2mdparser=jsonschema2md.Parser(examples_as_yaml=False,show_examples="all",)withopen("./examples/food.json","r")asjson_file:md_lines=parser.parse_schema(json.load(json_file))print(''.join(md_lines))Optionsexamples-as-yaml: Parse examples in YAML-format instead of JSON. (bool, default:False)show-examples: Parse examples for only the main object, only properties, or all.
(str, defaultall, options:object,properties,all)pre-commit hookYou can use the pre-commit hook with:repos:-repo:https://github.com/sbrunner/jsonschema2mdrev:<version># Use the ref you want to point athooks:-id:jsonschema2mdfiles:schema.jsonargs:---pre-commit-schema.json-schema.mdContributingBugs, questions or suggestions? Feel free to post an issue in theissue trackeror to make a pull
request! SeeContributing.mdfor more info.Install the pre-commit hooks:pipinstallpre-commit
pre-commitinstall--allow-missing-configChangelogSeeChangelog.md.
Package: jsonschema2md2
jsonschema2mdConvert JSON Schemas to simple, human-readable Markdown documentation.For example:{"$id":"https://example.com/person.schema.json","$schema":"http://json-schema.org/draft-07/schema#","title":"Person","description":"JSON Schema for a person object.","type":"object","properties":{"firstName":{"type":"string","description":"The person's first name."},"lastName":{"type":"string","description":"The person's last name."}}}will be converted to:PersonJSON Schema for a person object.PropertiesfirstName(string): The person's first name.lastName(string): The person's last name.See theexamplesdirectory for more elaborate examples.InstallationInstall with pippipinstalljsonschema2mdUsageFrom the CLIjsonschema2md[OPTIONS]<input.json><output.md>From Pythonimportjsonimportjsonschema2mdparser=jsonschema2md.Parser(examples_as_yaml=False,show_examples="all",)withopen("./examples/food.json","r")asjson_file:md_lines=parser.parse_schema(json.load(json_file))print(''.join(md_lines))Optionsexamples-as-yaml: Parse examples in YAML-format instead of JSON. (bool, default:False)show-examples: Parse examples for only the main object, only properties, or all.
(str, defaultall, options:object,properties,all)pre-commit hookYou can use the pre-commit hook with:repos:-repo:https://github.com/sbrunner/jsonschema2mdrev:<version># Use the ref you want to point athooks:-id:jsonschema2mdfiles:schema.jsonargs:---pre-commit-schema.json-schema.mdContributingBugs, questions or suggestions? Feel free to post an issue in theissue trackeror to make a pull
request! SeeContributing.mdfor more info.Install the pre-commit hooks:pipinstallpre-commit
pre-commitinstall--allow-missing-configChangelogSeeChangelog.md.
Package: jsonschema2popo
# JSONSCHEMA2POPOA converter to extract ‘Plain Old Python Object’ classes from JSON Schema files.
Currenty compatible with python 3.4+## Installationpip install jsonschema2popo## UsageBasic:jsonschema2popo -o /path/to/output_file.py /path/to/json_schema.jsonobject JSON encoding:import jsong = GeneratedClass()
json.dumps(g.as_dict())
Package: jsonschema2rst
This project aims to parseJSON schemasorYAMLschemas in order to create
RestructuredText documentation.
Using a tool like Sphinx, it is possible to create high readable documentation
from the files generated, which are RST formatted text.The outcome RST can be customized by defining a blacklist in csv and using a
custom CSS file. that will inherit the Sphinx one. For the latter, an
example is provided.UsageTo createRSTfiles fromJSON schemas(orYAML) run the command:jsonschema2rstinput_folderoutput_folderThis command will take all JSON or YAML files in this path, sub-folders
included, and wll create a new directory - removing it if already exists -
where all parsed RST file will be placed.ExampleLet’s assume you run the following command:jsonschema2rstjson_folderrst_output_folderand also let’s assume the folderjson_foldercontains the fileurl.json, which contains the following schema:{
    "title": "URL of related document",
    "properties": {
        "description": {
            "type": "string"
        },
        "value": {
            "format": "url",
            "type": "string"
        }
    },
    "type": "object"
}As result,jsonschema2rstwill create a file calledurl.rstin
therst_output_folderthat will contain the following rst code:..contents::TableofContents..section-numbering::..container::section-titleurl.json..container::titleURLofrelateddocument**type**:``object``**Properties:**description_,value_..description:description+++++++++++**type**:``string``..value:value+++++**type**:``string``**format**:``url``ExtraIn case you want to generate HTML documentation using a tool likeSphinx, we
suggest you to try thecustom.cssfile in thecontributionfolder to make
your schemas documentation looking better. What you need is just replace the
default css used by Sphinx in theconf.pyfile with the one proposed, then
enjoy!
Package: jsonschema-builder
BuildJSON schemaseasily in Python.Seedocumentationfor more informations.Installationpip install jsonschema-builderUsageimportjsonschemaimportjsbschema=jsb.typed(jsb.schema(id='/schemas/myschema#',meta=jsb.draft04()),type='object',properties={'foo':jsb.typed(jsb.schema(),type='string'),'bar':jsb.typed(jsb.schema(),type='integer')})data={'foo':'bar','bar':42}jsonschema.validate(data,schema)
Package: jsonschema-cli
JsonSchema CLIA thin wrapper overPython Jsonschemato allow validating shcemas easily using simple CLI commands.Installingpip install jsonschema-cliSecurityThe$refresolving will automatically resolve to any path using basic$refnotation:{"$ref":"my-custom.json#...."}That means that when using this tool, an attacker may do the following:{"$ref":"../../../../all-my-secrets.json"}To make sure this doesn't happen:When using this tool in a backend server, make sure the file access is scoped.Don't run JSONSCHEMAS without sanitizing paths.Treat all un-knwon user input as evil.This has no actual current  affect other than loading the contets of secrets into memory of the process.
But may lead to misfortune if not addressed.UsgaeUsingjsonschema-cli --helpusage:jsonschema-cli[-h]{validate}...

Awrapperaroundhttps://github.com/Julian/jsonschematovalidateJSONusingtheCLI

positionalarguments:{validate}ValidatethetjsondatawithaschemavalidateValidate

optionalarguments:-h,--helpshowthishelpmessageandexitValidateUsingjsonschema-cli validate --helpusage:jsonschema-clivalidate[-h]schema_file_or_stringdata_file_or_string

positionalarguments:schema_file_or_stringTheschemayouwanttousetovalidatethedatadata_file_or_stringThedatayouwantvalidatedbytheschema

optionalarguments:-h,--helpshowthishelpmessageandexitExamples# Returns no errors on stdout, no output needed on success (just exit code 0 is enough)jsonschema-clivalidate'{"properties": {"number": {"type": "integer"}}, "required": ["number"]}''{"number": 123}'# Has an error, "number" is now "123" instead of 123, an integer is expected.jsonschema-clivalidate'{"properties": {"number": {"type": "integer"}}, "required": ["number"]}''{"number": "123"}'>'123'isnotoftype'integer'>
>Failedvalidating'type'inschema['properties']['number']:
>{'type':'integer'}>
>Oninstance['number']:
>'123'Load YAMLThe CLI command can read YAML and validate both schema and data written in YAML# Returns no errors on stdout, no output needed on success (just exit code 0 is enough)SCHEMA="properties:number:type: integer"DATA="number: 123"jsonschema-clivalidate"$SCHEMA""$DATA"# Has an error, "number" is now "123" instead of 123, an integer is expected.SCHEMA="properties:number:type: integer"DATA="number: \"123\""jsonschema-clivalidate"$SCHEMA""$DATA">'123'isnotoftype'integer'>
>Failedvalidating'type'inschema['properties']['number']:
>{'type':'integer'}>
>Oninstance['number']:
>'123'
Package: jsonschema-codelane
jsonschemais an implementation ofJSON Schemafor Python (supporting 2.7+ including Python 3).>>>fromjsonschemaimportvalidate>>># A sample schema, like what we'd get from json.load()>>>schema={..."type":"object",..."properties":{..."price":{"type":"number"},..."name":{"type":"string"},...},...}>>># If no exception is raised by validate(), the instance is valid.>>>validate(instance={"name":"Eggs","price":34.99},schema=schema)>>>validate(...instance={"name":"Eggs","price":"Invalid"},schema=schema,...)# doctest: +IGNORE_EXCEPTION_DETAILTraceback(mostrecentcalllast):...ValidationError:'Invalid'isnotoftype'number'It can also be used from console:$jsonschema-isample.jsonsample.schemaFeaturesFull support forDraft 7,Draft 6,Draft 4andDraft 3Lazy validationthat can iteratively reportallvalidation errors.Programmatic queryingof which properties or items failed validation.Installationjsonschemais available onPyPI. You can install usingpip:$pipinstalljsonschemaDemoTryjsonschemainteractively in this online demo:Online demo Notebook will look similar to this:Release Notesv3.1 brings support for ECMA 262 dialect regular expressions
throughout schemas, as recommended by the specification. Big
thanks to @Zac-HD for authoring support in a newjs-regexlibrary.Running the Test SuiteIf you havetoxinstalled (perhaps viapip install toxor your
package manager), runningtoxin the directory of your source
checkout will runjsonschema’s test suite on all of the versions
of Pythonjsonschemasupports. If you don’t have all of the
versions thatjsonschemais tested under, you’ll likely want to run
usingtox’s--skip-missing-interpretersoption.Of course you’re also free to just run the tests on a single version with your
favorite test runner. The tests live in thejsonschema.testspackage.Benchmarksjsonschema’s benchmarks make use ofpyperf.Running them can be done viatox-eperf, or by invoking thepyperfcommands externally (after ensuring that both it andjsonschemaitself are
installed):$ python -m pyperf jsonschema/benchmarks/test_suite.py --hist --output results.jsonTo compare to a previous run, use:$ python -m pyperf compare_to --table reference.json results.jsonSee thepyperfdocumentation for more details.CommunityThere’s amailing listfor this implementation on Google Groups.Please join, and feel free to send questions there.ContributingI’m Julian Berman.jsonschemais onGitHub.Get in touch, via GitHub or otherwise, if you’ve got something to contribute,
it’d be most welcome!You can also generally find me on Freenode (nick:tos9) in various
channels, including#python.If you feel overwhelmingly grateful, you can also woo me with beer money
via Google Pay with the email in my GitHub profile.And for companies who appreciatejsonschemaand its continued support
and growth,jsonschemais also now supportable viaTideLift.
Package: jsonschema-converter
JSONSchema ConverterJSONSchema Converter is a tool that performs
conversions from a json-schema file to pydantic classesinstallationpipinstalljsonschema-converterrequirementspydantic>=2.5.3
loguru>=0.7.1usagejsonschema-convert --file_name chem_comp_schema.jsonexamplesyou can find examples of jsonschema input and pydantic classes output in the examples folder on github
Package: jsonschema-default
jsonschema-instanceA Python package that creates default objects from a JSON schema.NoteThis is not a validator. Inputs should be valid JSON schemas. For Python you can use thejsonschemapackage to validate schemas.Installationpip install jsonschema-defaultUsageimportjsonschema_defaultdefault_obj=jsonschema_default.create_from("<schema>")DevelopmentInstall and configurePoetrypipinstall--userpoetrySeeInstallationfor the official guide.Install the dependencies using# Configure poetry to create a local venv directorypoetryconfigvirtualenvs.in-projecttruepoetryinstall
Package: json-schema-discovery
Database-agnostic JSON schema discoveryQuickly get insight into the general structure of a large set of JSON files by creating a structure summary showing the type and frequency of objects keyQuickstartStart withEmptyor by passing a python object tomake_schema()Merge a schema onto another using+=(also accepts python objects on the right hand side)Visualize the resulting schema withdumps()or by printing the objectGet a detailed tabulated view of the overall structure withstatistics()
Package: json-schema-enforcer
JSON schema enforcerTable of ContentsIntroductionKey FeaturesInstallationUsageExample JSON SchemaPotential Use CasesIntroductionjson-schema-enforcer is a Python package that allows you to progressively validate a JSON string against a JSON schema. With this package, you can check if a JSON string adheres to the schema and if it is complete, even if the string is not fully formed. This is particularly useful when working with large language models to constraint text generation.This project was created out of spite for the lack of a similar feature inOpenAI ChatGPT's function calling, to prove that creating something like this is very easy. It uses the simplified JSON schema specification, similar to what OpenAI does. Please note that the code implementation probably does not adhere to best practices, as it is primarily an experimental showcase by someone who isn't skilled in creating programming language parsers.Key FeaturesParses a JSON schema and validates a string against itDetermines if the returned JSON is valid (matches the schema and optional formatting)Determines if the JSON string is complete and provides the index of the last characterInstallationYou can install json-schema-enforcer using pip:pipinstalljson-schema-enforcerUsageTo use json-schema-enforcer in your Python project, follow these steps:importjson_schema_enforcer# Parse the schemaparser=json_schema_enforcer.parser_for_schema(schema)# Check if the parser is validifparserisNone:raiseValueError("Invalid JSON schema")# Validate the JSON stringvalidated=parser.validate(maybe_json_string)# Print the validation resultprint(validated.valid)# Whether it adheres to the schemaprint("complete"ifvalidated.end_indexelse"incomplete")Example JSON SchemaYou can use the following example JSON schema as a reference when working with json-schema-enforcer:{"type":"object","properties":{"name":{"type":"string","maxLength":20},"age":{"type":"integer"},"preferred_animal":{"type":"string","enum":["cat","dog"]}},"required":["name","age"]}Potential Use CasesConstraining text generation with large language models; example:local-llm-function-calling, a project that allows you to constrain generation with any huggingface model
Package: json-schema-env-validator
JSON Schema Application Environment Configuration and ValidationThis package allows you to validate application environment variables that are
used for configuration with JSON schemas.It is extremely useful to use with Docker/kubernetes where you might have
quite a bit of configuration originating from environment variables; however,
it also provides a nice generic way to define and validate any application
configuration with JSON Schema.UsageFirst, define a JSON Schema file(env-schema.json):{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"db_uri":{"type":"string","title":"AMQP host"}},"required":["db_uri"]}Then, validate your environment config(export DB_URI=postgresql://localhost:5432):importenviralsettings=enviral.validate_env('env-schema.json')settings['db_uri']Validate with multiple files:importenviralsettings=enviral.validate_env('env-schema.json','package:validation-file.json')You can also validate existing objects against JSON schema files:importenviralenviral.validate_object({"db_uri":"postgresql://localhost:5432"},'env-schema.json')Or command line validate:json-schema-env-validatorenv-schema.jsonpackage:validation-file.jsonDevelopmentpipinstall-rrequirements.txt
pipinstall-e.
./bin/pre-commitinstall