File: atd-language-interoperability.rst

package info (click to toggle)
ocaml-atd 2.16.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,768 kB
  • sloc: ml: 45,944; python: 827; sh: 339; makefile: 306; cpp: 195; java: 76
file content (77 lines) | stat: -rw-r--r-- 2,047 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
=================================
Interoperability with other tools
=================================

JSON Schema
-----------

ATD type definitions can be translated to
`JSON Schema <https://json-schema.org/>`_
with ``atdcat``. The user must specify the main type on the command
line since ATD doesn't have a notion of main type or root type.
This can be useful for target languages that are not yet supported by
ATD or for educational purposes.

Example
^^^^^^^

Input: ATD file ``message.atd``::

  type msg = {
    subject: string;
    ?body: string option;
    ~attachments: attachment list;
  }

  type attachment = [
    | Image of string
    | Virus
  ]

Conversion to JSON Schema::

  $ atdcat -jsonschema msg message.atd -o message.schema.json

Output: JSON Schema file ``message.schema.json``::

  {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "description": "Translated by atdcat from 'message.atd'",
    "type": "object",
    "required": [ "subject" ],
    "properties": {
      "subject": { "type": "string" },
      "body": { "type": "string" },
      "attachments": {
        "type": "array",
        "items": { "$ref": "#/definitions/attachment" }
      }
    },
    "definitions": {
      "attachment": {
        "oneOf": [
          {
            "type": "array",
            "minItems": 2,
            "items": false,
            "prefixItems": [ { "const": "Image" }, { "type": "string" } ]
          },
          { "const": "Virus" }
        ]
      }
    }
  }

The ``jsonschema`` tool (Python implementation) can validate JSON data
using the JSON Schema file that we generated. For example, passing an
empty object ``{}`` correctly results in an error telling us the ``subject``
field is missing::

  $ jsonschema message.json -i <(echo '{}')
  {}: 'subject' is a required property

With valid JSON input such as
``{"subject": "hello", "attachments": ["Virus"]}``, the command
exits successfully and silently::

  $ jsonschema message.json -i <(echo '{"subject": "hello", "attachments": ["Virus"]}')