JSONSchema2PoPo2 3.0.3__tar.gz → 3.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. jsonschema2popo2-3.1.0/PKG-INFO +225 -0
  2. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/changelog.md +44 -0
  3. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/__init__.py +1 -1
  4. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/classes.py +13 -0
  5. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/go/go.py +4 -1
  6. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/go/go_struct.tmpl +4 -4
  7. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/js/js.py +14 -1
  8. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/js/js_class.tmpl +11 -23
  9. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/jsonschema2popo.py +203 -1
  10. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/python/python.py +4 -1
  11. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/python/python_class.tmpl +7 -7
  12. JSONSchema2PoPo2-3.0.3/PKG-INFO +0 -208
  13. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/JSONSchema2PoPo2.egg-info/SOURCES.txt +0 -0
  14. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/LICENSE.txt +0 -0
  15. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/MANIFEST.in +0 -0
  16. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/README.md +0 -0
  17. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/__main__.py +0 -0
  18. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/go/__init__.py +0 -0
  19. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/js/__init__.py +0 -0
  20. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/jsonschema2popo/python/__init__.py +0 -0
  21. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/setup.cfg +0 -0
  22. {JSONSchema2PoPo2-3.0.3 → jsonschema2popo2-3.1.0}/setup.py +0 -0
@@ -0,0 +1,225 @@
1
+ Metadata-Version: 2.4
2
+ Name: JSONSchema2PoPo2
3
+ Version: 3.1.0
4
+ Summary: Converts a JSON Schema to a Plain Old Python Object class
5
+ Home-page: https://github.com/mikedombo/JSONSchema2PoPo2
6
+ Author: Michael Dombrowski
7
+ Author-email: michael@mikedombrowski.com
8
+ License: MIT License
9
+ Keywords: python json-schema code-generator
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Topic :: Software Development :: Build Tools
14
+ Classifier: Programming Language :: Python :: 3.4
15
+ Classifier: Programming Language :: Python :: 3.5
16
+ Classifier: Programming Language :: Python :: 3.6
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.4
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE.txt
25
+ Requires-Dist: Jinja2>=2.11.3
26
+ Requires-Dist: networkx==2.4
27
+ Provides-Extra: format-js
28
+ Requires-Dist: jsbeautifier; extra == "format-js"
29
+ Provides-Extra: format-python
30
+ Requires-Dist: black; extra == "format-python"
31
+ Dynamic: author
32
+ Dynamic: author-email
33
+ Dynamic: classifier
34
+ Dynamic: description
35
+ Dynamic: description-content-type
36
+ Dynamic: home-page
37
+ Dynamic: keywords
38
+ Dynamic: license
39
+ Dynamic: license-file
40
+ Dynamic: provides-extra
41
+ Dynamic: requires-dist
42
+ Dynamic: requires-python
43
+ Dynamic: summary
44
+
45
+ # JSONSchema2PoPo2
46
+
47
+ *Forked from [github.com/frx08/jsonschema2popo](https://github.com/frx08/jsonschema2popo)*
48
+
49
+ A converter to extract 'Plain Old Python Object' classes from JSON Schema files. Similar to the Java
50
+ project [JSONSchema2PoJo](https://github.com/joelittlejohn/jsonschema2pojo/).
51
+
52
+ [![PyPI version](https://badge.fury.io/py/JSONSchema2PoPo2.svg)](https://pypi.org/project/JSONSchema2PoPo2/) [![Python package](https://github.com/MikeDombo/JSONSchema2PoPo2/workflows/Python%20package/badge.svg?branch=master)](https://github.com/MikeDombo/JSONSchema2PoPo2/actions?query=workflow%3A"Python+package")
53
+
54
+ ## Generated Code Compatibility
55
+
56
+ | Language | Feature | Version Compatibility | Reason |
57
+ | -------- | ------- | --------------------- | ------ |
58
+ | Python | Basic generation | Any Python | N/A |
59
+ | Python | Using Enums | \>= Python 3.4 | Uses [Enum](https://docs.python.org/3/library/enum.html) type |
60
+ | Python | Using Extends | \>= Python 3.0 | Uses new style Python class for inheritance |
61
+ | Python | Using Types | \>= Python 3.5 | Uses Python [type hints](https://www.python.org/dev/peps/pep-0484/) in code
62
+ | | | |
63
+ | JavaScript | Basic Generation | \>= ES2019 (\>= NodeJS 12.x) | Uses ES [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) and [private fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields)
64
+ | | | |
65
+ | Go | Basic Generation | Any Go | N/A |
66
+
67
+ ## Installation
68
+
69
+ ```
70
+ pip install jsonschema2popo2
71
+ ```
72
+
73
+ ## Usage
74
+
75
+ ### Basic:
76
+
77
+ ```
78
+ jsonschema2popo2 -o /path/to/output_file.py /path/to/json_schema.json
79
+ ```
80
+
81
+ ### Options:
82
+
83
+ - -o, --output-file - Generated file path.
84
+ - -jt, --custom-template - Path to custom Jinja template file (relative to CWD).
85
+ - -t, --use-types - Add MyPy typings. (Python only)
86
+ - -ct, --constructor-type-check - Validate provided types in constructor. Default only type checks when setting property
87
+ values and not when setting them in the constructor. (Python and JavaScript only)
88
+ - -s, --use-slots - Add a `__slots__` to each generated class to be more memory efficient. (Python only)
89
+ - --no-generate-from-definitions - Don't generate any classes from the "definitions" section of the schema.
90
+ - --no-generate-from-root-object - Don't generate any classes from the root of the schema.
91
+ - -tp, --translate-properties - Translate property names to be snake_case. With this enabled, inner classes will no
92
+ longer be prefixed by "_" since their names won't collide with the property name.
93
+ - -l, --language - Language to generate in. Choose "python", "js", "go", a python file, or a python module. When
94
+ using a python file or module, the module must expose `Plugin` as a class which extends and implements `CodeGenPlugin`.
95
+ - --namespace-path - Namespace path to be prepended to the @memberOf for JSDoc. (JavaScript only)
96
+ - --package-name - Package name for generated code. Default is "generated". (Go only)
97
+ - --version - Show the current version number.
98
+
99
+ ### Encode Generated Object to JSON:
100
+
101
+ **Python**
102
+
103
+ ```python
104
+ import json
105
+
106
+ g = GeneratedClass()
107
+ json.dumps(g.as_dict())
108
+ ```
109
+
110
+ **JavaScript**
111
+
112
+ ```javascript
113
+ g = new GeneratedClass();
114
+ JSON.stringify(g.asMap());
115
+ ```
116
+
117
+ **Go**
118
+
119
+ ```go
120
+ g := generated.GeneratedClass{};
121
+ str, err := json.Marshal(g)
122
+ ```
123
+
124
+ ### Decode JSON into Generated Object:
125
+
126
+ **Python**
127
+
128
+ ```python
129
+ import json
130
+
131
+ g = GeneratedClass.from_dict(json.loads(data))
132
+ ```
133
+
134
+ **JavaScript**
135
+
136
+ ```javascript
137
+ const g = GeneratedClass.fromMap(JSON.parse(data));
138
+ ```
139
+
140
+ **Go**
141
+
142
+ ```go
143
+ var g generated.GeneratedClass
144
+ err := json.Unmarshal(data, &g)
145
+ ```
146
+
147
+ ### JSON Schema Format
148
+
149
+ This library is largely compatible with JSONSchema2PoJo and how that library reads the JSON Schema to generate Java.
150
+ Specifically, for enumerations, this library supports setting the `javaEnumNames` array in JSON Schema for an enum to
151
+ give names to the enum values that will be generated in the Python output.
152
+
153
+ If you want to generate an object with a property that accepts any map/dictionary, then simply have `"type": "object"`in
154
+ the schema and do not add any properties to that definition. In this case, no new class will be generated, instead that
155
+ property's type will be `dict` in Python, `Object` in JavaScript, and `map[string]interface{}` in Go (`encoding/json` in
156
+ Go doesn't support `map[interace{}]interface{}`).
157
+
158
+ #### Example JSON Schema Documents
159
+
160
+ **Schema with references and enum**
161
+
162
+ ```json
163
+ {
164
+ "definitions": {
165
+ "Enum1": {
166
+ "description": "My favorite Enum!",
167
+ "type": "integer",
168
+ "enum": [
169
+ 1,
170
+ 2,
171
+ 3
172
+ ],
173
+ "javaEnumNames": [
174
+ "First",
175
+ "Second",
176
+ "Third"
177
+ ]
178
+ },
179
+ "Obj1": {
180
+ "type": "object",
181
+ "properties": {
182
+ "prop1": {
183
+ "type": "string"
184
+ },
185
+ "prop2": {
186
+ "$ref": "#/definitions/Enum1"
187
+ }
188
+ }
189
+ },
190
+ "Obj2": {
191
+ "type": "object",
192
+ "properties": {
193
+ "obj1": {
194
+ "$ref": "#/definitions/Obj1"
195
+ }
196
+ }
197
+ }
198
+ }
199
+ }
200
+ ```
201
+
202
+ #### Generated Documentation
203
+
204
+ When you provide a `"description"` in the JSON Schema, then that description will be applied in docstrings in the
205
+ generated code. For example, in the example above, the enum will have a docstring which says `My favorite enum!`.
206
+
207
+ You can also choose to add documentation for yourself in the schema document using the `"$comment"` key, which is simply
208
+ ignored by this tool. In this way, you can have public documentation in the `description`, and anything you want to keep
209
+ private can go in the `$comment`.
210
+
211
+ ### Customizing Generated Code
212
+
213
+ There are two ways to customize the output code which this project generates: you may use your own code generation
214
+ template, or you may implement a code generation plugin _and_ code generation template. I would suggest that you go
215
+ the whole way to implementing a code generation plugin since it isn't much additional work and can give you great
216
+ benefits.
217
+
218
+ #### Example Code Generation Plugin
219
+
220
+ Take as an example our
221
+ [builtin Go plugin](https://github.com/MikeDombo/JSONSchema2PoPo2/blob/468ea0881557dd98c831cae173f0bcd2ea73ac72/jsonschema2popo/go/go.py).
222
+ This plugin is simply a single Python file along with a template file. The Python code implements the
223
+ `CodeGenPlugin` interface which allows it to add more arguments to the command line options and then make those new
224
+ values available to the template file. The plugin can also provide more functions to be called from the Jinja
225
+ template which makes developing a template far simpler.
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.1.0
4
+
5
+ - Fix [#24](https://github.com/MikeDombo/JSONSchema2PoPo2/issues/24): values from the schema (defaults, `format`,
6
+ `pattern`, validations, enum values and descriptions) are no longer pasted into the generated Python, JavaScript and
7
+ Go code unescaped, so they can't break out of a string literal or comment, or run as code. Output for valid schemas
8
+ is otherwise unchanged.
9
+ - Names that the built-in generators emit as identifiers (types, properties and enum members) must now be valid
10
+ identifiers in the target language. Otherwise generation stops with a clear error instead of writing broken code.
11
+ Custom templates (`-jt`) and plugins are not checked.
12
+
13
+ ### Behavior changes
14
+
15
+ - JavaScript: a string default on a `"type": "string"` property is now always emitted as a string. Previously it was
16
+ pasted in as code, so `"default": "5"` became the number `5`, `"null"` became `null`, and `"pending"` threw a
17
+ `ReferenceError` when the object was constructed.
18
+ - Where values used to be pasted in as code (defaults of non-string properties, validations such as `maximum`, and
19
+ values of non-string enums), a string that is not a number or a plain name (such as `True` or `Color.RED`) is now
20
+ emitted as a string.
21
+
22
+ ## 3.0.3
23
+
24
+ - Type names are no longer lowercased when `-tp`/`--translate-properties` is on. Only property names are translated;
25
+ type names just have `.` and `-` replaced with `_`
26
+ ([#21](https://github.com/MikeDombo/JSONSchema2PoPo2/pull/21))
27
+
28
+ ## 3.0.2
29
+
30
+ - Fixed command line parsing so that `-tp`/`--translate-properties` is not forced on
31
+ ([#20](https://github.com/MikeDombo/JSONSchema2PoPo2/pull/20))
32
+
3
33
  ## 3.0.1
4
34
 
5
35
  - Rename any usage of `.` or `-` in a JSON property since no programming language can handle those characters in identifiers. Contributed by
@@ -97,6 +127,11 @@ The generated code is supposed to be entirely unchanged. Please open an issue if
97
127
  - Bugfix for `as_dict` and `from_dict` when translating property names so that the output dictionary has the original
98
128
  property names for `as_dict` and using original property names from the input dictionary for `from_dict`
99
129
 
130
+ ## 2.0.14
131
+
132
+ - `as_dict` and `from_dict` use the original property names from the schema when property names are translated
133
+ (completed in 2.0.15)
134
+
100
135
  ## 2.0.13
101
136
 
102
137
  - Add option to translate property names into snake_case which is more Pythonic
@@ -137,6 +172,15 @@ The generated code is supposed to be entirely unchanged. Please open an issue if
137
172
 
138
173
  - Added comments to classes and properties based on the `description` field of the schema
139
174
 
175
+ ## 2.0.4
176
+
177
+ - Removed type checks from `from_dict`
178
+ - Properties with `media.binaryEncoding: "base64"` now use `bytes` instead of `bytearray`
179
+
180
+ ## 2.0.3
181
+
182
+ - Fixed detection of `media.binaryEncoding: "base64"`, which was looked up in the wrong place in the schema
183
+
140
184
  ## 2.0.2
141
185
 
142
186
  - Enabled generating classes with `bytes` type properties when the schema has `media.binaryEncoding: "base64"` set
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env python
2
2
 
3
- __version__ = "3.0.3"
3
+ __version__ = "3.1.0"
4
4
  version = __version__
@@ -1,10 +1,16 @@
1
1
  import abc
2
2
  import argparse
3
+ import re
3
4
  from typing import Dict, Any, List, Set, Optional, Callable, Type
4
5
 
5
6
  extra_generation_options = dict()
6
7
 
7
8
 
9
+ def is_identifier(name: str) -> bool:
10
+ """Unicode letters, digits and '_', not starting with a digit. Never matches quotes, operators or whitespace."""
11
+ return name.isidentifier() or re.fullmatch(r"[^\W\d]\w*", name) is not None
12
+
13
+
8
14
  def translate_properties():
9
15
  return extra_generation_options.get("translate_properties", False)
10
16
 
@@ -311,5 +317,12 @@ class CodeGenPlugin(abc.ABC):
311
317
  def extra_jinja_inputs(self) -> Dict[str, Any]:
312
318
  return {}
313
319
 
320
+ def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
321
+ """
322
+ Whether a name from the schema can be emitted as an identifier by this plugin's template. Plugins that
323
+ emit names as identifiers should reject anything that could end one (quotes, operators, whitespace...).
324
+ """
325
+ return True
326
+
314
327
  def after_generation(self, filename: Optional[str] = None) -> None:
315
328
  pass
@@ -3,7 +3,7 @@ import os
3
3
  from typing import Dict, Callable, Any
4
4
 
5
5
  from jsonschema2popo import version
6
- from jsonschema2popo.classes import CodeGenPlugin
6
+ from jsonschema2popo.classes import CodeGenPlugin, is_identifier
7
7
  from jsonschema2popo.python.python import Python
8
8
 
9
9
 
@@ -27,6 +27,9 @@ class Go(CodeGenPlugin):
27
27
  def extra_jinja_inputs(self) -> Dict[str, Any]:
28
28
  return {"package_name": self.package_name}
29
29
 
30
+ def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
31
+ return is_identifier(name)
32
+
30
33
  def template(self) -> str:
31
34
  return "go_struct.tmpl"
32
35
 
@@ -5,7 +5,7 @@
5
5
  {{ (model.full_name_python_path()) | replace(".", "")}}
6
6
  {%- endmacro -%}
7
7
  {% macro translate_bool(bool) %}{% if bool is sameas True %}true{% elif bool is sameas False %}false{% elif bool is none
8
- %}nil{% elif bool is number %}int64({{bool}}){% else %}{{ bool }}{% endif %}{% endmacro %}
8
+ %}nil{% elif bool is number %}int64({{bool}}){% else %}{{ bool | json_value }}{% endif %}{% endmacro %}
9
9
 
10
10
  {%- macro translate_type(prop) -%}
11
11
  {% if prop is string %}
@@ -44,13 +44,13 @@ package {{package_name}}
44
44
  {% if not model.type == "enum" %}
45
45
  var {{go_name(model)}}Formats = map[string]string {
46
46
  {% for prop in model.properties if prop.format %}
47
- "{{trn(prop.name)}}": "{{prop.format}}",
47
+ "{{trn(prop.name)}}": {{ prop.format | json_quote('"', 'go') }},
48
48
  {% endfor %}
49
49
  }
50
50
  var {{go_name(model)}}Validations = map[string]map[string]interface{} {
51
51
  {% for prop in model.properties if prop.validations %}
52
52
  "{{ trn(prop.name) }}": { {% for type, value in prop.validations.items() %}"{{ type }}": {% if type ==
53
- "pattern" %}"{{ value | replace ("\\", "\\\\") | replace("\"", "\\\"")}}"{% else %}{{ translate_bool(value) }}{%endif%},{% endfor %}},
53
+ "pattern" %}{{ value | string | json_literal }}{% else %}{{ translate_bool(value) }}{%endif%},{% endfor %}},
54
54
  {% endfor %}
55
55
  }
56
56
 
@@ -83,7 +83,7 @@ var {{ go_name(model) }}Options = struct{
83
83
  {% endfor %}
84
84
  }{
85
85
  {% for name, value in model.values.items() %}
86
- {{name}}: {% if model.value_type.type == "string" %}"{{value}}"{% else %}{{value}}{% endif %},
86
+ {{name}}: {% if model.value_type.type == "string" %}{{ value | json_quote('"', 'go') }}{% else %}{{ value | json_value }}{% endif %},
87
87
 
88
88
  {% endfor %}
89
89
 
@@ -1,9 +1,16 @@
1
1
  import argparse
2
2
  import os
3
+ import re
3
4
  from typing import Union, Dict, Callable, Any
4
5
 
5
6
  from jsonschema2popo import version
6
- from jsonschema2popo.classes import Definition, ListNode, ReferenceNode, CodeGenPlugin
7
+ from jsonschema2popo.classes import (
8
+ Definition,
9
+ ListNode,
10
+ ReferenceNode,
11
+ CodeGenPlugin,
12
+ is_identifier,
13
+ )
7
14
  from jsonschema2popo.jsonschema2popo import string_to_type
8
15
  from jsonschema2popo.python.python import Python
9
16
 
@@ -42,6 +49,12 @@ class JS(CodeGenPlugin):
42
49
  def template(self) -> str:
43
50
  return "js_class.tmpl"
44
51
 
52
+ def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
53
+ # JS identifiers may contain '$', and enum member names are object keys, which may also be numbers
54
+ if enum_member and re.fullmatch(r"\d+(\.\d*)?([eE][+-]?\d+)?", name):
55
+ return True
56
+ return is_identifier(name.replace("$", "_"))
57
+
45
58
  def jinja_globals(self) -> Dict[str, Callable]:
46
59
  return {"jsdoc_type": self.jsdoc_type, "python_type": Python.python_type}
47
60
 
@@ -5,7 +5,7 @@
5
5
  or prop.definition, relative_to=relativeTo, with_namespace=withNamespace)) }}{% if get_type(prop, sub=False, module=True) == "Array" %}[]{% endif %}{% raw %}}{% endraw %}
6
6
  {%- endmacro -%}
7
7
  {% macro jsdoc_param(name, prop) %}
8
- @param {{ name }} {{ jsdoc_typ(prop, withNamespace=True) }} {% if prop.comment %}{{ prop.comment | indent(7) }}{% endif %}
8
+ @param {{ name }} {{ jsdoc_typ(prop, withNamespace=True) }} {% if prop.comment %}{{ prop.comment | block_comment | indent(7) }}{% endif %}
9
9
  {% endmacro %}
10
10
  {%- macro translate_type(type, module=False) -%}
11
11
  {%- if type is none -%}
@@ -39,18 +39,6 @@ typeof {{ var }} === "number"
39
39
  {%- endif -%}
40
40
  {%- endmacro -%}
41
41
 
42
- {% macro translate_bool(bool) %}
43
- {% if bool is sameas True %}
44
- true
45
- {% elif bool is sameas False %}
46
- false
47
- {% elif bool is none %}
48
- null
49
- {% else %}
50
- {{ bool }}
51
- {% endif %}
52
- {% endmacro %}
53
-
54
42
  {% macro get_type(prop, relativeTo=None, sub=True, module=False) -%}{{ translate_type(python_type(sub and prop.definition|attr("item_type") or prop.definition or None, relative_to=relativeTo))-}}{%-
55
43
  endmacro -%}
56
44
  {% macro type_check(prop, name=None, relativeTo=None) %}
@@ -68,7 +56,7 @@ if ({{ name or trn(prop.name) }} !== null && !{{ name or trn(prop.name) }}.every
68
56
 
69
57
  {%- macro generate_class(model) -%}
70
58
  /**
71
- * {% if model.comment %}{{ model.comment | indent(3) }}{% endif %}
59
+ * {% if model.comment %}{{ model.comment | block_comment | indent(3) }}{% endif %}
72
60
 
73
61
  *
74
62
  * @class
@@ -88,7 +76,7 @@ class {{model.python_type_name}}{% if model.extends %} extends {{ model.extends
88
76
  */
89
77
  constructor(
90
78
  {% for prop in model.properties %}
91
- {{trn(prop.name)}}={{translate_bool(prop.default)}},
79
+ {{trn(prop.name)}}={% if prop.definition.string_type == "string" and prop.default is not none %}{{ prop.default | json_literal }}{% else %}{{ prop.default | json_value }}{% endif %},
92
80
  {% endfor %}
93
81
  {% if model.extends %}
94
82
  ...superArgs
@@ -118,7 +106,7 @@ class {{model.python_type_name}}{% if model.extends %} extends {{ model.extends
118
106
 
119
107
  {% for prop in model.properties %}
120
108
  /**
121
- {% if prop.comment %} * {{ prop.comment | indent(7) }}
109
+ {% if prop.comment %} * {{ prop.comment | block_comment | indent(7) }}
122
110
  {% endif %}
123
111
  * @returns {{ jsdoc_typ(prop, relativeTo=None, withNamespace=True) }}
124
112
 
@@ -190,14 +178,14 @@ class {{model.python_type_name}}{% if model.extends %} extends {{ model.extends
190
178
  Object.defineProperty({{ model.full_name_python_path() }}, "options", {
191
179
  value: {
192
180
  {% for name, value in model.values.items() %}
193
- {{ name }}: {% if model.value_type.type == "string" %}"{{value}}"{% else %}{{value}}{% endif %},
181
+ {{ name }}: {% if model.value_type.type == "string" %}{{ value | json_quote('"') }}{% else %}{{ value | json_value }}{% endif %},
194
182
  {% endfor %}
195
183
  }
196
184
  });
197
185
  Object.defineProperty({{ model.full_name_python_path() }}, "optionsFlipped", {
198
186
  value: {
199
187
  {% for name, value in model.values.items() %}
200
- {% if model.value_type.type == "string" %}"{{value}}"{% else %}{{value}}{% endif %}: "{{ name }}",
188
+ {% if model.value_type.type == "string" %}{{ value | json_quote('"') }}{% else %}{{ value | json_value }}{% endif %}: "{{ name }}",
201
189
  {% endfor %}
202
190
  }
203
191
  });
@@ -209,7 +197,7 @@ Object.defineProperty({{ model.full_name_python_path() }}, "optionsFlipped", {
209
197
  * @readonly
210
198
  */
211
199
  Object.defineProperty({{ model.full_name_python_path() }}, "{{ name }}", {
212
- value: new {{ model.full_name_python_path() }}({% if model.value_type.type == "string" %}"{{value}}"{% else %}{{value}}{% endif %})
200
+ value: new {{ model.full_name_python_path() }}({% if model.value_type.type == "string" %}{{ value | json_quote('"') }}{% else %}{{ value | json_value }}{% endif %})
213
201
  });
214
202
  {% endfor %}
215
203
  {% endif %}
@@ -233,14 +221,14 @@ Object.defineProperty({{ model.full_name_python_path() }}, "typesMap", {
233
221
  Object.defineProperty({{ model.full_name_python_path() }}, "formatsMap", {
234
222
  value: {
235
223
  {% for prop in model.properties if prop.format %}
236
- {{trn(prop.name)}}: '{{prop.format}}',
224
+ {{trn(prop.name)}}: {{ prop.format | json_quote("'") }},
237
225
  {% endfor %}
238
226
  }
239
227
  });
240
228
  Object.defineProperty({{ model.full_name_python_path() }}, "validationsMap", {
241
229
  value: {
242
230
  {% for prop in model.properties if prop.validations %}
243
- '{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}/{{ value }}/{% else %}{{ translate_bool(value) }}{% endif %},{% endfor %}},
231
+ '{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}{{ value | js_regex }}{% else %}{{ value | json_value }}{% endif %},{% endfor %}},
244
232
  {% endfor %}
245
233
  }
246
234
  });
@@ -258,7 +246,7 @@ Object.defineProperty({{ model.full_name_python_path() }}, "validationsMap", {
258
246
  * @type {% raw %}{{{% endraw %}
259
247
 
260
248
  {% for model in models %}
261
- {{model.name}}: {{model.name}}{% if not loop.last %},
249
+ {{model.python_type_name}}: {{model.python_type_name}}{% if not loop.last %},
262
250
  {% endif %}{% endfor %}
263
251
 
264
252
  {% raw %}}}{% endraw %}
@@ -266,6 +254,6 @@ Object.defineProperty({{ model.full_name_python_path() }}, "validationsMap", {
266
254
  */
267
255
  module.exports = {
268
256
  {%- for model in models %}
269
- {{model.name}},
257
+ {{model.python_type_name}},
270
258
  {% endfor %}
271
259
  };
@@ -31,6 +31,141 @@ from . import __version__
31
31
 
32
32
  logger = logging.getLogger("main")
33
33
 
34
+ # Strings that were always pasted into the code unquoted and are kept that way (ignoring surrounding whitespace):
35
+ # a number in any notation the languages accept (0x10, 1_000, 1e-3, 10n...), or a plain dotted name such as
36
+ # True, null, Color.RED or -Infinity. Neither can call anything; any other string is quoted.
37
+ UNQUOTED_RE = re.compile(
38
+ r"[+-]?(\.?\d[\w.]*([eE][+-]\d\w*)?|[^\W\d]\w*(\.[^\W\d]\w*)*)"
39
+ )
40
+
41
+ # Characters that end a single-line string literal, and whether a backslash may escape them (line continuation)
42
+ LINE_BREAKS = {"python": ("\r\n", True), "js": ("\r\n", True), "go": ("\n", False)}
43
+
44
+
45
+ def is_closed_docstring(s: str) -> bool:
46
+ """
47
+ Whether s can go between triple quotes as-is: no unescaped \"\"\" inside it. The template puts a newline after
48
+ the text, so a trailing backslash can't escape the closing quotes.
49
+ """
50
+ i = 0
51
+ while i < len(s):
52
+ if s[i] == "\\":
53
+ i += 2
54
+ elif s.startswith('"""', i):
55
+ return False
56
+ else:
57
+ i += 1
58
+ return True
59
+
60
+
61
+ def is_closed_js_regex(s: str) -> bool:
62
+ """Whether /s/ is one complete JS regex literal (like old_literal, plus [...] classes)."""
63
+ if not s or s[0] == "*":
64
+ return False
65
+ in_class = False
66
+ i = 0
67
+ while i < len(s):
68
+ c = s[i]
69
+ if c in "\r\n\u2028\u2029":
70
+ return False
71
+ if c == "\\":
72
+ if i + 1 >= len(s) or s[i + 1] in "\r\n\u2028\u2029":
73
+ return False
74
+ i += 2
75
+ continue
76
+ if c == "[":
77
+ in_class = True
78
+ elif c == "]":
79
+ in_class = False
80
+ elif c == "/" and not in_class:
81
+ return False
82
+ i += 1
83
+ # An unclosed [ class would swallow the closing / and whatever follows it on the line
84
+ return not in_class
85
+
86
+
87
+ def json_literal(v) -> str:
88
+ # U+2028/U+2029 are valid in JS strings but jsbeautifier turns them into line breaks, so escape them
89
+ return (
90
+ json.dumps(v, ensure_ascii=False)
91
+ .replace("\u2028", "\\u2028")
92
+ .replace("\u2029", "\\u2029")
93
+ )
94
+
95
+
96
+ def old_literal(s: str, quote: str, language: str) -> Optional[str]:
97
+ """
98
+ quote + s + quote, as the templates used to emit it, if that is one complete string literal in the language:
99
+ every quote inside s is escaped, s does not end in an escaping backslash, and line breaks only appear as
100
+ line continuations where the language allows them. Escape sequences then mean exactly what they used to.
101
+ Raw U+2028/U+2029 are escaped (same value) because jsbeautifier would turn them into line breaks.
102
+ Returns None if the old form was not a complete literal.
103
+ """
104
+ breaks, continuation = LINE_BREAKS[language]
105
+ out = []
106
+ i = 0
107
+ while i < len(s):
108
+ c = s[i]
109
+ if c == "\\":
110
+ if i + 1 >= len(s) or (s[i + 1] in breaks and not continuation):
111
+ return None
112
+ j = i + 3 if s.startswith("\r\n", i + 1) else i + 2
113
+ out.append(s[i:j])
114
+ i = j
115
+ continue
116
+ if s.startswith(quote, i) or c in breaks:
117
+ return None
118
+ out.append("\\u%04x" % ord(c) if c in "\u2028\u2029" else c)
119
+ i += 1
120
+ return quote + "".join(out) + quote
121
+
122
+
123
+ def py_quote(v, quote: str) -> str:
124
+ """A Python string literal for v: the old quote + v + quote when that was already a complete literal."""
125
+ s = str(v)
126
+ return old_literal(s, quote, "python") or repr(s)
127
+
128
+
129
+ def json_quote(v, quote: str, language: str = "js") -> str:
130
+ """A JS/Go string literal for v: the old quote + v + quote when that was already a complete literal."""
131
+ s = str(v)
132
+ return old_literal(s, quote, language) or json_literal(s)
133
+
134
+
135
+ def unquoted(v) -> Optional[str]:
136
+ """The text a string value used to be pasted in as, if it is a number or a plain name; otherwise None."""
137
+ t = v.strip()
138
+ return t if UNQUOTED_RE.fullmatch(t) else None
139
+
140
+
141
+ def py_value(v) -> str:
142
+ """Python source for a value that was emitted unquoted: as before, except strings that aren't numbers or names are quoted."""
143
+ if isinstance(v, str):
144
+ return unquoted(v) or repr(v)
145
+ return str(v)
146
+
147
+
148
+ def json_value(v) -> str:
149
+ """JS/Go source for a value that was emitted unquoted: numbers and names as before, everything else as JSON."""
150
+ if isinstance(v, str):
151
+ return unquoted(v) or json_literal(v)
152
+ return json_literal(v)
153
+
154
+
155
+ def py_docstring(s: str) -> str:
156
+ """Docstring text, unchanged unless it would end the docstring early; then every '"' is escaped."""
157
+ return s if is_closed_docstring(s) else s.replace('"', '\\"')
158
+
159
+
160
+ def js_regex(v) -> str:
161
+ s = str(v)
162
+ return (
163
+ "/" + s + "/"
164
+ if is_closed_js_regex(s)
165
+ else "new RegExp(" + json_literal(s) + ")"
166
+ )
167
+
168
+
34
169
  J2P_TYPES = {
35
170
  "string": str,
36
171
  "integer": int,
@@ -101,6 +236,17 @@ class JsonSchema2Popo:
101
236
  find, replace, s
102
237
  )
103
238
  self.jinja.globals["trn"] = self.maybe_translate_property_name
239
+ # Values from the schema are emitted as literals, never pasted into the generated source as code.
240
+ self.jinja.filters.update(
241
+ py_quote=py_quote,
242
+ py_value=py_value,
243
+ py_docstring=py_docstring,
244
+ json_literal=json_literal,
245
+ json_quote=json_quote,
246
+ json_value=json_value,
247
+ js_regex=js_regex,
248
+ )
249
+ self.jinja.filters["block_comment"] = lambda s: s.replace("*/", "*\\/")
104
250
  self.jinja.filters["trn"] = self.maybe_translate_property_name
105
251
 
106
252
  jinja_globals = self.module.jinja_globals()
@@ -405,12 +551,14 @@ class JsonSchema2Popo:
405
551
  return model
406
552
 
407
553
  def write_file(self, filename):
554
+ if not self.custom_template:
555
+ self.check_names()
408
556
  template = self.custom_template or self.module.template()
409
557
  self.jinja.get_template(template).stream(
410
558
  models=self.definitions,
411
559
  enum_used=self.enum_used,
412
560
  list_used=self.list_used,
413
- **self.module.extra_jinja_inputs()
561
+ **self.module.extra_jinja_inputs(),
414
562
  ).dump(filename)
415
563
  if hasattr(filename, "close"):
416
564
  filename.close()
@@ -422,6 +570,60 @@ class JsonSchema2Popo:
422
570
  s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
423
571
  return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
424
572
 
573
+ def check_names(self):
574
+ """Check every name the built-in templates emit as an identifier, for what is actually generated."""
575
+ seen = set()
576
+
577
+ def check_path(d: Definition):
578
+ # A type is emitted by its full path, e.g. Parent._child
579
+ for a in d.ancestors():
580
+ if a.name is not None:
581
+ self.check_identifier(a.name, "Type or property")
582
+
583
+ def visit(d: Optional[Definition]):
584
+ if d is None or id(d) in seen:
585
+ return
586
+ seen.add(id(d))
587
+ check_path(d)
588
+ if isinstance(d, ReferenceNode):
589
+ if d.value is not None:
590
+ check_path(d.value)
591
+ return
592
+ if getattr(d, "extends", None) is not None:
593
+ check_path(d.extends)
594
+ if isinstance(d, ListNode):
595
+ visit(d.item_type)
596
+ if isinstance(d, EnumNode):
597
+ for name in d.values:
598
+ self.check_identifier(
599
+ name,
600
+ "Enum member",
601
+ enum_member=True,
602
+ hint=" Enum member names are the enum values, or javaEnumNames if given.",
603
+ )
604
+ for p in getattr(d, "properties", None) or []:
605
+ self.check_identifier(p.name, "Type or property")
606
+ visit(p.definition)
607
+ for c in d.children:
608
+ visit(c)
609
+
610
+ for model in self.definitions:
611
+ visit(model)
612
+
613
+ def check_identifier(self, name, kind: str, enum_member=False, hint=""):
614
+ """
615
+ Names from the schema are emitted as identifiers, so they must be identifiers in the target language.
616
+ Type and property names have '-' and '.' replaced with '_' first; enum member names are used as-is.
617
+ """
618
+ candidate = str(name)
619
+ if not enum_member:
620
+ candidate = candidate.replace("-", "_").replace(".", "_")
621
+ if not self.module.is_valid_identifier(candidate, enum_member=enum_member):
622
+ raise ValueError(
623
+ f"{kind} name {name!r} cannot be used as an identifier in the generated "
624
+ f"{self.module.plugin_name()} code.{hint}"
625
+ )
626
+
425
627
  def translate_type_name(self, name):
426
628
  name = name.replace("-", "_").replace(".", "_")
427
629
  return name
@@ -4,7 +4,7 @@ import pathlib
4
4
  from typing import Union, Dict, Callable, Any
5
5
 
6
6
  from jsonschema2popo import version
7
- from jsonschema2popo.classes import Definition, ListNode, CodeGenPlugin
7
+ from jsonschema2popo.classes import Definition, ListNode, CodeGenPlugin, is_identifier
8
8
  from jsonschema2popo.jsonschema2popo import string_to_type
9
9
 
10
10
 
@@ -46,6 +46,9 @@ class Python(CodeGenPlugin):
46
46
  "use_types": self.use_types,
47
47
  }
48
48
 
49
+ def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
50
+ return is_identifier(name)
51
+
49
52
  def template(self) -> str:
50
53
  return "python_class.tmpl"
51
54
 
@@ -25,7 +25,7 @@ from typing import List
25
25
  class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif %}{% if model.extends %}({{ model.extends.full_name_python_path()}}){% endif %}:
26
26
  {% if model.comment %}
27
27
  """
28
- {{ model.comment | indent(4) }}
28
+ {{ model.comment | py_docstring | indent(4) }}
29
29
  """
30
30
  {% endif %}
31
31
  {% for child in model.children %}
@@ -38,7 +38,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
38
38
 
39
39
  {% if model.type == "enum" %}
40
40
  {% for name, value in model.values.items() %}
41
- {{name}} = {% if model.value_type.type == "string" %}"{{value}}"{% else %}{{value}}{% endif %}
41
+ {{name}} = {% if model.value_type.type == "string" %}{{ value | py_quote('"') }}{% else %}{{ value | py_value }}{% endif %}
42
42
 
43
43
  {% endfor %}
44
44
  {% endif %}
@@ -51,12 +51,12 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
51
51
  }
52
52
  _formats_map = {
53
53
  {% for prop in model.properties if prop.format %}
54
- '{{trn(prop.name)}}': '{{prop.format}}',
54
+ '{{trn(prop.name)}}': {{ prop.format | py_quote("'") }},
55
55
  {% endfor %}
56
56
  }
57
57
  _validations_map = {
58
58
  {% for prop in model.properties if prop.validations %}
59
- '{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}'{{ value }}'{% else %}{{ value }}{% endif %},{% endfor %}},
59
+ '{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}{{ value | py_quote("'") }}{% else %}{{ value | py_value }}{% endif %},{% endfor %}},
60
60
  {% endfor %}
61
61
  }
62
62
  {% endif %}
@@ -67,7 +67,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
67
67
  , *args
68
68
  {% endif %}
69
69
  {% for prop in model.properties %}
70
- , {{trn(prop.name)}}{% if use_types %}: {{ get_typing(prop, relativeTo=model) }}{% endif %}={% if prop.definition.string_type == "string" and prop.default is not none %}'{{prop.default}}'{% else %}{{prop.default}}{% endif %}
70
+ , {{trn(prop.name)}}{% if use_types %}: {{ get_typing(prop, relativeTo=model) }}{% endif %}={% if prop.definition.string_type == "string" and prop.default is not none %}{{ prop.default | py_quote("'") }}{% else %}{{ prop.default | py_value }}{% endif %}
71
71
  {% endfor %}
72
72
  {% if model.extends %}
73
73
  , **kwargs
@@ -77,7 +77,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
77
77
  """
78
78
  {% for prop in model.properties %}
79
79
  {% if prop.comment %}
80
- :param {{ trn(prop.name) }}: {{ prop.comment | indent(12) }}
80
+ :param {{ trn(prop.name) }}: {{ prop.comment | py_docstring | indent(12) }}
81
81
  {% endif %}
82
82
  {% endfor %}
83
83
  """
@@ -105,7 +105,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
105
105
  {{trn(prop.name)}} = property(_get_{{trn(prop.name)}}, _set_{{trn(prop.name)}})
106
106
  {% if prop.comment %}
107
107
  """
108
- {{ prop.comment | indent(4) }}
108
+ {{ prop.comment | py_docstring | indent(4) }}
109
109
  """
110
110
  {% endif %}
111
111
 
@@ -1,208 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: JSONSchema2PoPo2
3
- Version: 3.0.3
4
- Summary: Converts a JSON Schema to a Plain Old Python Object class
5
- Home-page: https://github.com/mikedombo/JSONSchema2PoPo2
6
- Author: Michael Dombrowski
7
- Author-email: michael@mikedombrowski.com
8
- License: MIT License
9
- Description: # JSONSchema2PoPo2
10
-
11
- *Forked from [github.com/frx08/jsonschema2popo](https://github.com/frx08/jsonschema2popo)*
12
-
13
- A converter to extract 'Plain Old Python Object' classes from JSON Schema files. Similar to the Java
14
- project [JSONSchema2PoJo](https://github.com/joelittlejohn/jsonschema2pojo/).
15
-
16
- [![PyPI version](https://badge.fury.io/py/JSONSchema2PoPo2.svg)](https://pypi.org/project/JSONSchema2PoPo2/) [![Python package](https://github.com/MikeDombo/JSONSchema2PoPo2/workflows/Python%20package/badge.svg?branch=master)](https://github.com/MikeDombo/JSONSchema2PoPo2/actions?query=workflow%3A"Python+package")
17
-
18
- ## Generated Code Compatibility
19
-
20
- | Language | Feature | Version Compatibility | Reason |
21
- | -------- | ------- | --------------------- | ------ |
22
- | Python | Basic generation | Any Python | N/A |
23
- | Python | Using Enums | \>= Python 3.4 | Uses [Enum](https://docs.python.org/3/library/enum.html) type |
24
- | Python | Using Extends | \>= Python 3.0 | Uses new style Python class for inheritance |
25
- | Python | Using Types | \>= Python 3.5 | Uses Python [type hints](https://www.python.org/dev/peps/pep-0484/) in code
26
- | | | |
27
- | JavaScript | Basic Generation | \>= ES2019 (\>= NodeJS 12.x) | Uses ES [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) and [private fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields)
28
- | | | |
29
- | Go | Basic Generation | Any Go | N/A |
30
-
31
- ## Installation
32
-
33
- ```
34
- pip install jsonschema2popo2
35
- ```
36
-
37
- ## Usage
38
-
39
- ### Basic:
40
-
41
- ```
42
- jsonschema2popo2 -o /path/to/output_file.py /path/to/json_schema.json
43
- ```
44
-
45
- ### Options:
46
-
47
- - -o, --output-file - Generated file path.
48
- - -jt, --custom-template - Path to custom Jinja template file (relative to CWD).
49
- - -t, --use-types - Add MyPy typings. (Python only)
50
- - -ct, --constructor-type-check - Validate provided types in constructor. Default only type checks when setting property
51
- values and not when setting them in the constructor. (Python and JavaScript only)
52
- - -s, --use-slots - Add a `__slots__` to each generated class to be more memory efficient. (Python only)
53
- - --no-generate-from-definitions - Don't generate any classes from the "definitions" section of the schema.
54
- - --no-generate-from-root-object - Don't generate any classes from the root of the schema.
55
- - -tp, --translate-properties - Translate property names to be snake_case. With this enabled, inner classes will no
56
- longer be prefixed by "_" since their names won't collide with the property name.
57
- - -l, --language - Language to generate in. Choose "python", "js", "go", a python file, or a python module. When
58
- using a python file or module, the module must expose `Plugin` as a class which extends and implements `CodeGenPlugin`.
59
- - --namespace-path - Namespace path to be prepended to the @memberOf for JSDoc. (JavaScript only)
60
- - --package-name - Package name for generated code. Default is "generated". (Go only)
61
- - --version - Show the current version number.
62
-
63
- ### Encode Generated Object to JSON:
64
-
65
- **Python**
66
-
67
- ```python
68
- import json
69
-
70
- g = GeneratedClass()
71
- json.dumps(g.as_dict())
72
- ```
73
-
74
- **JavaScript**
75
-
76
- ```javascript
77
- g = new GeneratedClass();
78
- JSON.stringify(g.asMap());
79
- ```
80
-
81
- **Go**
82
-
83
- ```go
84
- g := generated.GeneratedClass{};
85
- str, err := json.Marshal(g)
86
- ```
87
-
88
- ### Decode JSON into Generated Object:
89
-
90
- **Python**
91
-
92
- ```python
93
- import json
94
-
95
- g = GeneratedClass.from_dict(json.loads(data))
96
- ```
97
-
98
- **JavaScript**
99
-
100
- ```javascript
101
- const g = GeneratedClass.fromMap(JSON.parse(data));
102
- ```
103
-
104
- **Go**
105
-
106
- ```go
107
- var g generated.GeneratedClass
108
- err := json.Unmarshal(data, &g)
109
- ```
110
-
111
- ### JSON Schema Format
112
-
113
- This library is largely compatible with JSONSchema2PoJo and how that library reads the JSON Schema to generate Java.
114
- Specifically, for enumerations, this library supports setting the `javaEnumNames` array in JSON Schema for an enum to
115
- give names to the enum values that will be generated in the Python output.
116
-
117
- If you want to generate an object with a property that accepts any map/dictionary, then simply have `"type": "object"`in
118
- the schema and do not add any properties to that definition. In this case, no new class will be generated, instead that
119
- property's type will be `dict` in Python, `Object` in JavaScript, and `map[string]interface{}` in Go (`encoding/json` in
120
- Go doesn't support `map[interace{}]interface{}`).
121
-
122
- #### Example JSON Schema Documents
123
-
124
- **Schema with references and enum**
125
-
126
- ```json
127
- {
128
- "definitions": {
129
- "Enum1": {
130
- "description": "My favorite Enum!",
131
- "type": "integer",
132
- "enum": [
133
- 1,
134
- 2,
135
- 3
136
- ],
137
- "javaEnumNames": [
138
- "First",
139
- "Second",
140
- "Third"
141
- ]
142
- },
143
- "Obj1": {
144
- "type": "object",
145
- "properties": {
146
- "prop1": {
147
- "type": "string"
148
- },
149
- "prop2": {
150
- "$ref": "#/definitions/Enum1"
151
- }
152
- }
153
- },
154
- "Obj2": {
155
- "type": "object",
156
- "properties": {
157
- "obj1": {
158
- "$ref": "#/definitions/Obj1"
159
- }
160
- }
161
- }
162
- }
163
- }
164
- ```
165
-
166
- #### Generated Documentation
167
-
168
- When you provide a `"description"` in the JSON Schema, then that description will be applied in docstrings in the
169
- generated code. For example, in the example above, the enum will have a docstring which says `My favorite enum!`.
170
-
171
- You can also choose to add documentation for yourself in the schema document using the `"$comment"` key, which is simply
172
- ignored by this tool. In this way, you can have public documentation in the `description`, and anything you want to keep
173
- private can go in the `$comment`.
174
-
175
- ### Customizing Generated Code
176
-
177
- There are two ways to customize the output code which this project generates: you may use your own code generation
178
- template, or you may implement a code generation plugin _and_ code generation template. I would suggest that you go
179
- the whole way to implementing a code generation plugin since it isn't much additional work and can give you great
180
- benefits.
181
-
182
- #### Example Code Generation Plugin
183
-
184
- Take as an example our
185
- [builtin Go plugin](https://github.com/MikeDombo/JSONSchema2PoPo2/blob/468ea0881557dd98c831cae173f0bcd2ea73ac72/jsonschema2popo/go/go.py).
186
- This plugin is simply a single Python file along with a template file. The Python code implements the
187
- `CodeGenPlugin` interface which allows it to add more arguments to the command line options and then make those new
188
- values available to the template file. The plugin can also provide more functions to be called from the Jinja
189
- template which makes developing a template far simpler.
190
-
191
- Keywords: python json-schema code-generator
192
- Platform: UNKNOWN
193
- Classifier: Development Status :: 5 - Production/Stable
194
- Classifier: Intended Audience :: Developers
195
- Classifier: License :: OSI Approved :: MIT License
196
- Classifier: Topic :: Software Development :: Build Tools
197
- Classifier: Programming Language :: Python :: 3.4
198
- Classifier: Programming Language :: Python :: 3.5
199
- Classifier: Programming Language :: Python :: 3.6
200
- Classifier: Programming Language :: Python :: 3.7
201
- Classifier: Programming Language :: Python :: 3.8
202
- Classifier: Programming Language :: Python :: 3.9
203
- Classifier: Programming Language :: Python :: 3.10
204
- Classifier: Programming Language :: Python :: Implementation :: PyPy
205
- Requires-Python: >=3.4
206
- Description-Content-Type: text/markdown
207
- Provides-Extra: Format JS
208
- Provides-Extra: Format Python