Coder Social home page Coder Social logo

lnoor / sphinx-jsonschema Goto Github PK

View Code? Open in Web Editor NEW
71.0 71.0 23.0 134 KB

A Sphinx extension to display a JSON Schema

Home Page: http://sphinx-jsonschema.readthedocs.io

License: GNU General Public License v3.0

Python 100.00%
json-schema sphinx-doc sphinx-extension

sphinx-jsonschema's People

Contributors

baylessj avatar bubanoid avatar choldgraf avatar evilpuppetmaster avatar glennicholls avatar iamdbychkov avatar jag3773 avatar jenshnielsen avatar lnoor avatar shaded-enmity avatar spagh-eddie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sphinx-jsonschema's Issues

Fails to parse valid json files

Currently all schema files are loaded in with pyyaml. Yaml does not allow for lines to start with tabs, however lines beginning with whitespace are valid json.

This causes valid schemas to fail to parse

exception occurred:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/yaml/scanner.py", line 257, in fetch_more_tokens
    self.get_mark())
yaml.scanner.ScannerError: while scanning for the next token
found character '\t' that cannot start any token

Object examples and defaults render as "OrderedDict(...)"

If a schema contains examples or defaults for an object it's rendered out as "OrderedDict(...)".

For example, the following schema renders the examples and defaults as OrderedDict([(‘dimensions’, OrderedDict([(‘width’, 5), (‘height’, 10)]))]) and OrderedDict() respectively.

{
    "$schema": "http://json-schema.org/draft-04/schema",
    "id": "http://example.com/example.json",
    "type": "object",
    "title": "The root schema",
    "description": "The root schema comprises the entire JSON document.",
    "default": {},
    "examples": [
        {
            "dimensions": {
                "width": 5,
                "height": 10
            }
        }
    ],
    "required": [
        "dimensions"
    ],
    "properties": {
        "dimensions": {
            "id": "#/properties/dimensions",
            "type": "object",
            "title": "The dimensions schema",
            "description": "An explanation about the purpose of this instance.",
            "default": {},
            "examples": [
                {
                    "width": 5,
                    "height": 10
                }
            ],
            "required": [
                "width",
                "height"
            ],
            "properties": {
                "width": {
                    "id": "#/properties/dimensions/properties/width",
                    "type": "integer",
                    "title": "The width schema",
                    "description": "An explanation about the purpose of this instance.",
                    "default": 0,
                    "examples": [
                        5
                    ]
                },
                "height": {
                    "id": "#/properties/dimensions/properties/height",
                    "type": "integer",
                    "title": "The height schema",
                    "description": "An explanation about the purpose of this instance.",
                    "default": 0,
                    "examples": [
                        10
                    ]
                }
            },
            "additionalProperties": true
        }
    },
    "additionalProperties": true
}

Ideally this would be rendered out as json. If not maybe the ability to set them to not render at all would work? Currently in order to make the documentation look correct I have to remove any examples and defaults from objects, meaning I can't just use the same master json schemas I'm using for other tooling.

Underscore in pattern creates an unresolved reference

{
"title": "title",
"description": "description.",
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"mailbox": {
"description": "Full address of the mailbox [email protected]",
"type": "string",
"format": "email"
},
"recipients": {
"description": "List of email addresses to which incoming mail is forwarded.",
"type": "array",
"items": {
"type": "string",
"format": "email",
"pattern": "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
},
"minItems": 1
}
},
"additionalProperties": false,
"required": ["mailbox", "recipients"]
}

This schema-pattern creates an unresolved reference because of the included underscore. See attached image.
unresolved_reference

Support references

Allow "$ref" entries.

Extend the meta schema with key

  • "$$target" : "Labeled entry"
    Used in a referenced section. Forces the (sub)schema to be displayed as a separate schema.
    The value is used as the title of the (sub)schema and can be used when referencingthe (sub)schema.

  • "$ref" : "schema reference"
    The reference is replaced with a clickable link to the referenced (sub schema).

  • "$$display": "some label"
    The $$display property (when present) is used to include or exclude schemas whe displaying.
    The idea is that an external json file containing many schema definitions can be displayed on multiple pages by selecting which schemas are displayed based on the $$display property and the display_if option of the jsonreference directive.

Extend the jsonschema directive with an option called display_if.
Use the (required) string value of this option to match against the $$display property.

Update documentation (and include conf.py snippet).

Advanced styling of required parameters

instead of tag use something like or mark parent tag with CSS class to make it possibe to change text color/use background images or highlight them in other ways.

Handling of dependencies

It looks like this tool would be a great fit for some of our documentation purposes. However, it seems the tool does not currently handle dependencies. Is this correct, or is there a way to include these in the output generated by the code?

No title with section header

Don't create a title field when the title duplicates the section header.
Do print the title in embedded schemas.

Add support for "up one level" relative paths

Relative paths don't support using "up one level" ../ syntax

In https://github.com/lnoor/sphinx-jsonschema/blob/master/sphinx-jsonschema/__init__.py#L64

                # file relative to the path of the current rst file
                dname = os.path.dirname(self.statemachine.input_lines.source(0))
                file_or_url = os.path.join(dname, file_or_url)

it would be really nice if relatives paths were actually supported. I'm building docs from /docs folder in a repo and want to ref a path to a json in the same repo outside the current documentation directory.

Bug in v1.16.4 when `lift_title=False` broke `auto_definitions`

With latest v1.16.4 and config-options:
"lift_title": False,
"lift_definitions": True,
"auto_reference": True,
"auto_target": True,

... then the auto_definitions=True does not work -- all definition references are reported as

WARNING: Unknown target name: "<schema-name>"

Turning lift_title=True fixes the problem, but then one cannot take advantage of this setting.

Configurable `definitions` key

We're using the standard key $defs for definitions inside the schema, which I noticed didn't work well with the :lift_definitions: option. Following the "extending sphinx-jsonschema" I ended up doing this:

def _patched_sphinx_jsonschema_dispatch(self, schema, label=None):
    if '$defs' in schema:
        schema['definitions'] = schema['$defs']
    rows = _original_sphinx_jsonschema_dispatch(self, schema, label)
    return rows

sjs_wide_format = importlib.import_module("sphinx-jsonschema.wide_format")
_original_sphinx_jsonschema_dispatch = sjs_wide_format.WideFormat._dispatch  # type: ignore
sjs_wide_format.WideFormat._dispatch = _patched_sphinx_jsonschema_dispatch  # type: ignore

Which does what I need but I don't really like it from maintenance perspective. Would you be interested in a patch that introduces configurable key? Something like:

.. jsonschema: ...
   :definitions_key: $defs

Renders "null" default value as "None"

It is confusing that the following snippet:

        "dashboard_component_list": {
          "$id": "#root/profile/dashboard_component_list",
          "title": "Default component list",
          "anyOf": [{ "type": "null" }, { "type": "integer" }],
          "default": null
        }

Is rendered as:

image

There is no "None" type in JSON, it's Python way of calling it, and we're documenting JSON here, so "null" should be used instead to describe it.

The full schema:

https://github.com/WeblateOrg/weblate_schemas/blob/ffab5fd8e478ef2116591f0280583882831a372a/weblate_schemas/schemas/weblate-userdata.schema.json#L160

Rendered:

https://docs.weblate.org/en/latest/contributing/schemas.html#weblate-user-data-export

Properly implement /definitions

The whole /definitions section and references to it is currently disregarded.
The easiest way to implement it is to consider it a special case of the existing $ref resolving mechanism.

In order to implement this no changes to the referencing code is necessary.
But we do need to replace the (mostly non-existent) handling of the /definitions section.

Most straightforward solution is to treat each key under definitions as a new top level schema and call the renderer recursively for each one.
If the subschema is missing title and $$target entries these should be synthesized and included.

Problem in 1.16.4-5; producing LaTex Output

Hi - I can do make html but make latex fails with message as shown below. The JSON file is here: https://github.com/pnnl/tesp/blob/develop/doc/tso_schema.json and it's referenced just like .. jsonschema:: tso_schema.json

This had been producing both HTML and PDF on ReadTheDocs, but then the triggered builds began to fail. I just checked the JSON file on jsoneditoronline.org, and it seems okay. For now, I can work around this issue by using version 1.16.3.

Error after make latex using either 1.16.4 or 1.16.5
Exception occurred: File "/home/tom/.local/lib/python3.6/site-packages/sphinx/writers/latex.py", line 947, in <listcomp> underlined = [cell.row + cell.height == self.table.row + 1 for cell in cells] AttributeError: 'NoneType' object has no attribute 'row' The full traceback has been saved in /tmp/sphinx-err-_pnasj_l.log, if you want to report the issue to the developers. Please also report this if it was a user error, so that a better error message can be provided next time. A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks! Makefile:20: recipe for target 'latex' failed make: *** [latex] Error 2

Add parameter for max depth

Hello and thanks for this cool extension :)

How difficult would it be to add a parameter to choose how deep we want to read the schema?

Typically:

.. json-schema:: myfile.json
   :depth: 2

Thanks!

Break long (pattern) property names

patternProperty names have a tendency to get rather large.
Insert spaces around | separators allowing the parts of the regexp to spread over multiple lines.

Failing tests with NoneType object for app

When trying to run the tests, they all fail. Am I missing something?

PYTHONPATH=/home/abuild/rpmbuild/BUILDROOT/python-sphinx-jsonschema-1.16.7-0.x86_64/usr/lib/python3.6/site-packages
PYTHONDONTWRITEBYTECODE=1
pytest-3.6 --ignore=_build.python36 --ignore=_build.python38 -v --trace -rs
============================= test session starts ==============================
platform linux -- Python 3.6.13, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3.6
cachedir: .pytest_cache
rootdir: /home/abuild/rpmbuild/BUILD/sphinx-jsonschema-ab7262e105845c306604eef60803a76ec8ff955e
collecting ... collected 2 items

tests/test_overall.py::test_create ERROR                                 [ 50%]
tests/test_overall.py::test_string ERROR                                 [100%]

==================================== ERRORS ====================================
________________________ ERROR at setup of test_create _________________________

    @pytest.fixture
    def wideformat():
        state = Body(RSTStateMachine([], None))
        state.build_table = Mock()
        lineno = 1
        source = ''
        options = {}
        app = None
    
>       return wide_format.WideFormat(state, lineno, source, options, app)

tests/test_overall.py:21: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <sphinx-jsonschema.wide_format.WideFormat object at 0x7fd5da4f0e48>
state = <docutils.parsers.rst.states.Body object at 0x7fd5da4f04a8>, lineno = 1
source = '', options = {}, app = None

    def __init__(self, state, lineno, source, options, app):
        super(WideFormat, self).__init__()
        self.app = app
        self.trans = None
        self.lineno = lineno
        self.state = state
        self.filename = self._get_filename(source)
        self.nesting = 0
        self.ref_titles = {}
        self.target_pointer = '#'
    
        self.options = deepcopy(self.option_defaults)
>       self.options.update(app.config.jsonschema_options)
E       AttributeError: 'NoneType' object has no attribute 'config'

../../BUILDROOT/python-sphinx-jsonschema-1.16.7-0.x86_64/usr/lib/python3.6/site-packages/sphinx-jsonschema/wide_format.py:63: AttributeError
________________________ ERROR at setup of test_string _________________________

    @pytest.fixture
    def wideformat():
        state = Body(RSTStateMachine([], None))
        state.build_table = Mock()
        lineno = 1
        source = ''
        options = {}
        app = None
    
>       return wide_format.WideFormat(state, lineno, source, options, app)

tests/test_overall.py:21: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <sphinx-jsonschema.wide_format.WideFormat object at 0x7fd5da47f518>
state = <docutils.parsers.rst.states.Body object at 0x7fd5da47f198>, lineno = 1
source = '', options = {}, app = None

    def __init__(self, state, lineno, source, options, app):
        super(WideFormat, self).__init__()
        self.app = app
        self.trans = None
        self.lineno = lineno
        self.state = state
        self.filename = self._get_filename(source)
        self.nesting = 0
        self.ref_titles = {}
        self.target_pointer = '#'
    
        self.options = deepcopy(self.option_defaults)
>       self.options.update(app.config.jsonschema_options)
E       AttributeError: 'NoneType' object has no attribute 'config'

../../BUILDROOT/python-sphinx-jsonschema-1.16.7-0.x86_64/usr/lib/python3.6/site-packages/sphinx-jsonschema/wide_format.py:63: AttributeError
============================== 2 errors in 0.40s ===============================

Error when both target is in scheme and quotes in title

Installing earlier (1.12) version fixes the problem. So it is introduced in 1.13.

I didn't debug it deeply yet. I have ~40 schemas with linking each others. Looks like work of $ref tag is broken or I have some issue in my schemas.

I can provide more information or try to debug it later.

The full log of the error in console while generating doc:

exception:  while parsing a flow mappington.schema
  in "<unicode string>", line 80, column 14:
        "value": {
                 ^
expected ',' or '}', but got '<scalar>'
  in "<unicode string>", line 82, column 214:
     ... Optional: Yes (together with \\"variable\\")"
                                         ^
exception:  while parsing a flow sequenceock_definitions
  in "<unicode string>", line 64, column 19:
          "examples": [
                      ^
expected ',' or ']', but got '<scalar>'
  in "<unicode string>", line 65, column 23:
            " {\\n\\r  \\"type\\": \\"expression\\",\\n\\r ...
                          ^

Exception occurred:
  File "c:\program files\python37\lib\site-packages\jsonpointer.py", line 279, in walk
    raise JsonPointerException("member '%s' not found in %s" % (part, doc))
jsonpointer.JsonPointerException: member 'definitions' not found in {}
The full traceback has been saved in C:\Users\......\AppData\Local\Temp\sphinx-err-can9yg2j.log, if you want to report the issue to the developers.
Please also report this if it was a user error, so that a better error message can be provided next time.
A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks!
"ProjectName: Error during Sphinx run. Check correctness of json schemas. Error code == 2"

Multiline human-friendly descriptions

When maintaining JSON files, it's rather difficult to write long multi-line strings, for example in the description field. Sometimes I need to introduce table in documentation and it's nightmare to change such a code:

{
"description": "+------------+------------+-----------+ \n| Header 1   | Header 2   | Header 3  | \n+============+============+===========+ \n| body row 1 | column 2   | column 3  | \n+------------+------------+-----------+ \n| body row 2 | Cells may span columns.| \n+------------+------------+-----------+ \n| body row 3 | Cells may  | - Cells   | \n+------------+ span rows. | - contain | \n| body row 4 |            | - blocks. | \n+------------+------------+-----------+"
}

Make it possible to write description in more human-friendly way:

{
"description": [
  "+------------+------------+-----------+",
  "| Header 1   | Header 2   | Header 3  |",
  "+============+============+===========+",
  "| body row 1 | column 2   | column 3  |",
  "+------------+------------+-----------+",
  "| body row 2 | Cells may span columns.|",
  "+------------+------------+-----------+",
  "| body row 3 | Cells may  | - Cells   |",
  "+------------+ span rows. | - contain |",
  "| body row 4 |            | - blocks. |",
  "+------------+------------+-----------+"
]}

REF: allow to disable referencing code, to suppress warnings

It is common for JSON documents to define and $ref to a /definitions section within themselves.
But that habit does not bond very well with this useful extension (it needs a separate directive for each referenced definition, duplicating the work). Therefore i leave those internal references broken, and use this extension only for linking to external documents, rendering descriptions and presenting the document-structure.

Now in all my projects i have a test-case demanding that no warnings are raised when building the site.
For this extension i have to suppress too many warnings, irrelevant to this extension:

 suppress_warnings = ["ref.ref"]

Would it be hard to add a configuration-option to disable completely the linking code (even if that breaks external documents)?

relative path has to be specified to include local Schema files that should be in search path

I have a directory structure like follows:

project_root
+---doc
|   |   .gitignore
|   |   make.bat
|   |   Makefile
|   |
|   +---build
|   |
|   \---source
|       |   conf.py
|       |   example1.json
|       |   index.rst
|       |   SomeJSONSchemaFile.json
|       |
|       +---_static
|       \---_templates
+---src

If I want to include SomeJSONSchemaFile.json from folder source, I have to give the path as relative to the doc directory: .. jsonschema:: source/SomeJSONSchemaFile.json

Since I usually can include files in the source directory without giving the path to source, I would expect that I can do the same with jsonschema includes.

Warn if schema file cannot be read.

When a schema cannot be read (file inaccessible, improper format) it will result in an exception.
Generate a warning instead so that Sphinx continues processing instead of aborting.

Error when using the directive

Seems like some of the YAML additions introduced a bug:

Exception occurred:
File "../python3.6/site-packages/sphinx-jsonschema/init.py", line 108, in ordered_load
return result
UnboundLocalError: local variable 'result' referenced before assignment

I am guessing there is an exception and hence the result value is never assigned.

Schema representation is not updated when source file is updated

I load my JSON Schema from a local source file with
.. jsonschema:: source/SomeJSONSchemaFile.json

When I change the content SomeJSONSchemaFile.json and then rebuild the documentation, the changes are note represented in the output. Onlyh after a clean build the documentation shows the changes.

Hide some properties

Some properties in JSON-schemas are useful for JSON schema validation but are completely useless when placed to sphinx documentation. For example, I'd like to have the possibility to hide property "type" for all schemas in documentation because in my case it is always "object" and this only confuses documentation users.

:lift_description: only works on description; not on $$description key

/work/doc/category_list.rst:10: WARNING: Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/sphinx-jsonschema/wide_format.py", line 170, in _get_description
self.state.nested_parse(self._convert_content(schema['description']), self.lineno, node)
KeyError: 'description'

"no module named 'pointer'"

I can't get this extension to function with sphinx, I think because the json_pointer module isn't being installed properly. I pip installed it, but AFAIK the module doesn't have a setup.py file and isn't python 3 compatible. Am I looking in the wrong place for json_pointer?

Bug with combinators

There is a bug regarding the schema using combinators. If "type" is present at the same level than a "oneOf", it fails.

example:

{
    "oneOf": [
        { "type": "string", "enum": ["one"] },
        { "type": "string", "enum": ["two"] }
    ]
}

works, however:

{
    "type": "string"
    "oneOf": [
        { "enum": ["one"] },
        { "enum": ["two"] }
    ]
}

don't.

Best regards

Relative paths don't work inside sphinxcontrib.autohttp.flask docstrings

To quickly and easily build REST documentation for my Flask site I'm using sphinxcontrib.autohttp.flask. To document the JSON parts of the REST API I'm using your project.

I store examples and the schemas in the same folder under schemas and whilst literalinclude works your jsonschema doesn't.

  1. Install your package (sphinx-jsonschema), sphinxcontrib-httpdomain and Sphinx<4.0.0.
  2. Configure the conf.py:
    extensions = [
       ...,
       "sphinxcontrib.httpdomain",
       "sphinxcontrib.autohttp.flask",
       "sphinx-jsonschema",
    ]
  3. Symlink docs/path/to/folder/schemas to src/path/to/folder/schemas.
  4. Run Sphinx.
..  automodule:: path.to.folder
"""
..  autoflask:: path.to.folder:app
    :undoc-static:
"""

...

@app.route("/post", methods=["POST"])
def post():
    pass


PWD = pathlib.Path(__file__).parent
post.__doc__ = f"""
Test site to run unit and performance tests against.

..  works
..  literalinclude:: /path/to/folder/schemas/post_request.json

..  works
..  literalinclude:: schemas/post_request.schema.json

..  works (but I have to manully set ``__doc__`` as f-doc-strings aren't a thing)
..  jsonschema:: {PWD}/schemas/post_request.schema.json

..  doesn't work
..  jsonschema:: schemas/post_request.schema.json
"""

Note: Providing the absolute path you're trying to read from would be helpful for end users.

/path/to/folder/file.rst: WARNING: "jsonschema" directive encountered an IOError while loading file: schemas/post_request.schema.json
[Errno 2] No such file or directory: 'schemas/post_request.schema.json'

Empty oneOf, anyOf, allOf

Sometimes it is needed to set optional "required". Often it is reflected in schemas like this:

 "anyOf": [
    {
      "required": [ "object_id" ]
    },
    {
      "required": [ "result_id" ]
    }
  ]

In documentation it is shown as two empty list elements under "anyOf":
chrome_SKKnrgo2kG

Expected result: "anyOf", "oneOf", "allOf" and other fields should be hidden if there are only hidden properties under them (like "required").

Backslash cannot be displayed in html

page.rst

page
====
.. jsonschema:: sample.json

sample.json

{
  "type": "string",
  "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}

It becomes ^(([0-9]{3}))?[0-9]{3}-[0-9]{4}$ in browser.

duplication of description and type

The following

{
    "title": "Mandature",
    "description": "La mandature",
    
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "datePriseFonction": {
            "type": "string",
            "format": "date-time"
        },
        "causeFin": {
            "type": "string"
        },
        "premiereElection": {
            "type": "string"
        },
        "placeHemicycle": {
            "type": "string"
        },
        "mandatRemplaceRef": {
            "type": "string"
        }
    },
    
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "tricoteuses-assemblee/src/types/Mandature.json",
    "$$target": "tricoteuses-assemblee/src/types/Mandature.json"
}

Shows as (note the duplication of La mandature)

<div class="section" id="mandature">
<span id="tricoteuses-assemblee/src/types/mandature.json"></span><h2>Mandature<a class="headerlink" href="#mandature" title="Permalink to this headline">¶</a></h2>
<table class="docutils align-default">
<colgroup>
<col style="width: 33%" />
<col style="width: 33%" />
<col style="width: 33%" />
</colgroup>
<tbody>
<tr class="row-odd"><td colspan="3"><p>La mandature</p></td>
</tr>
<tr class="row-even"><td><p>type</p></td>
<td colspan="2"><p><em>object</em></p></td>
</tr>
<tr class="row-odd"><td colspan="3"><p>properties</p></td>
</tr>
<tr class="row-even"><td rowspan="2"><ul class="simple">
<li><p>datePriseFonction</p></li>
</ul>
</td>
<td><p>type</p></td>
<td><p><em>string</em></p></td>
</tr>
<tr class="row-odd"><td><p>format</p></td>
<td><p>date-time</p></td>
</tr>
<tr class="row-even"><td><ul class="simple">
<li><p>causeFin</p></li>
</ul>
</td>
<td><p>type</p></td>
<td><p><em>string</em></p></td>
</tr>
<tr class="row-odd"><td><ul class="simple">
<li><p>premiereElection</p></li>
</ul>
</td>
<td><p>type</p></td>
<td><p><em>string</em></p></td>
</tr>
<tr class="row-even"><td><ul class="simple">
<li><p>placeHemicycle</p></li>
</ul>
</td>
<td><p>type</p></td>
<td><p><em>string</em></p></td>
</tr>
<tr class="row-odd"><td><ul class="simple">
<li><p>mandatRemplaceRef</p></li>
</ul>
</td>
<td><p>type</p></td>
<td><p><em>string</em></p></td>
</tr>
<tr class="row-even"><td><p>additionalProperties</p></td>
<td colspan="2"><p>False</p></td>
</tr>
<tr class="row-odd"><td colspan="3"><p>La mandature</p></td>
</tr>
<tr class="row-even"><td><p>type</p></td>
<td colspan="2"><p><em>object</em></p></td>
</tr>
</tbody>
</table>
</div>

Schema doesn't get built unless there is something after it

I was trying to include a schema (written in YAML) in my documentation (built with Sphinx), but it did not work unless there was something under the jsonschema directive.

For example, if I put in my RST file:

.. jsonschema:: example1.yml

.. jsonschema:: example2.yml

only example1 would build. If the document ended with .. jsonschema:: example1.yml, it would not build, but if it was

.. jsonschema:: example1.yml

example text

it would build.

If this is not just a problem on my end, this may be something you want to fix or document.

Keep keys in order

Use an OrderedDict when decoding JSON so that the keys are maintained in the order the appear in the JSON file.

sphinx-jsonschema (un)safe for parallel processing?

Building documentation with Sphinx 4.0.1 and sphinx-jsonschema 1.16.8 always yields the following warnings:

WARNING: the sphinx-jsonschema extension does not declare if it is safe for parallel reading, assuming it
         isn't - please ask the extension author to check and make it explicit
WARNING: doing serial read

This is problematic when sphinx-build is run with the -W flag because in turn, all builds will fail even if there are no "actual" warnings. Is there any way to get around this warning? Would it be an option for the maintainer(s) to declare what the first warning demands?

REF: `lift_title` config & directive flag

(thanks for #46 👍)
I would like this library to copy the logic for controling the inclusion of the description of a schema in the table (or the text above it),
with lift_description, but for title property, with a respective property lift_title.

My use case is to embed schema-tables in argument definitions:

       :param f_up_threshold:
            .. jsonschema:: data-schema.yaml#/properties/f_up_threshold

But if the specific property has a title, the rendered result is like this:
Screenshot from 2020-09-20 16-05-07

While i would like is something simpler, without the section-title beneath the argument, like this:
image

Compact presentation of OneOf and friends

At the moment the array containing the options for OneOf is presented as the other arrays where the
value is preceded with a mostly empty column.
Remove this column so the presentation takes less horizontal space.

Reference not work

Hello, i'm trying to build rst using schema with "$ref" structure, and for some reason my references always undefined:

assembling single document... services/catalog <unknown>:1: WARNING: undefined label: #/definitions/bind (if the link has no caption the label must precede a section header)
<unknown>:1: WARNING: undefined label: #/definitions/bz (if the link has no caption the label must precede a section header)

Exact jsonschema:

title: server role
description: "server configurathion"
type: object
additionalProperties: false

required:
- enabled
- user

properties:
  enabled:
    description: |-
      Enables server configurathion.
    type: boolean
  bind:
    description: Specifies servcive listen on configurathion.
    type: object
    properties:
      "test1": { "$ref": "#/definitions/bind" }
  bindtest2:
    description: Specifies servcive listen on configurathion.
    type: object
    "$ref": '#/definitions/bz'


definitions:
  bind:
    '$$target': [ '#/definitions/bind' , "#/definitions/bz" ]
    type: object
    properties:
      port:
        description: |-
          Specifies the local addresses should listen on.
        type: integer
      address:
        description: Specifies the port on which the server listens for connections. Multiple options are permitted.
        type: string
        example: 127.0.0.1 192.168.1.1

Version list

pip freeze |grep -i "sphinx\|yaml"
PyYAML==3.12
Sphinx==1.6.6
sphinx-jsonschema==1.4
sphinxcontrib-websupport==1.0.1

Could you suggest me somthing ?)

1.17.0 fails with `KeyError: 'hide_key'`

When upgrading sphinx-jsonschema from 1.16.11 to 1.17.0 (see WeblateOrg/weblate#6806), I get following crash:

Error: /home/runner/work/weblate/weblate/docs/contributing/schemas.rst:8: WARNING: Traceback (most recent call last):

  File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/sphinx-jsonschema/__init__.py", line 166, in run
    if self.options['hide_key']:
KeyError: 'hide_key'

Probably related to #65

Complement

This issue is not actually a real issue. It's more of a complement; I just wanted to share that I'm amazed at how useful this library is, and how well it works. I started having to deal with JSONSchema in a project, and, while documenting it, I wanted something to help me generating the schemas and embed them in the documentation, so this library fits like a glove. I installed the dependency, added the extension to the Sphinx configs and voilà!, JSONSchemas available in my docs! Just like that, it just works!

Thanks a lot, guys, this project rocks! :-)

(Feel free to close this ticket, I just wanted to share my feelings for your great work.)

Support `examples`

Since Draft 7 we have examples.

The examples keyword is a place to provide an array of examples that validate against the schema. This isn’t used for validation, but may help with explaining the effect and purpose of the schema to a reader. Each entry should validate against the schema in which is resides, but that isn’t strictly required.

Would be nice to have them displayed in the documentation table. too.

RFE: Global options for permanently enabling directive flags

The itch

The new flags for auto reference/target & definitions work just fine, no need to fiddle with this extension anymore.
Thank you!

But now i need to repeat the useful flags allover:

.. jsonschema:: some_schema.yaml
    :lift_definitions:
    :auto_reference:
    :auto_target:

The scratch

Would it be possible to add an extension-option so that we can permanently imply the flags for the directive?

To explain what i mean, adding this code in extension's setup() would do the trick
(of course it would also needs changes in the directive's logic when parsing the flags):

setup(app):
    app.add_config_value('jsonschema_default_directive_flags', '', 'env')
    ...

And a possible content for the user's docs/conf.pywould be the space-separated flags to enable
(assuming they are all boolean flags):

jsonschema_default_directive_flags = "lift_definitions auto_reference auto_target"

... and the user then could simply write:

.. jsonschema:: some_schema.yaml

Does that make sense?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.