json-structure 0.1.8__tar.gz → 0.1.10__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: json-structure
3
- Version: 0.1.8
3
+ Version: 0.1.10
4
4
  Summary: Validators for JSON Structure schemas and instances
5
5
  Project-URL: Homepage, https://json-structure.org
6
6
  Project-URL: Documentation, https://github.com/json-structure/sdk
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.1.8'
32
- __version_tuple__ = version_tuple = (0, 1, 8)
31
+ __version__ = version = '0.1.10'
32
+ __version_tuple__ = version_tuple = (0, 1, 10)
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -1,4 +1,8 @@
1
1
  # encoding: utf-8
2
+ # Suppress the runpy module import warning when running as python -m
3
+ import warnings
4
+ warnings.filterwarnings("ignore", message="'json_structure.*' found in sys.modules")
5
+
2
6
  """
3
7
  json_structure_instance_validator.py
4
8
 
@@ -443,13 +447,15 @@ class JSONStructureInstanceValidator:
443
447
  self.validate_instance(instance[prop], prop_schema, f"{path}/{prop}")
444
448
  if "additionalProperties" in schema:
445
449
  addl = schema["additionalProperties"]
450
+ # $schema is a built-in property allowed in all instances
451
+ reserved_props = {"$schema"}
446
452
  if addl is False:
447
453
  for key in instance.keys():
448
- if key not in props:
454
+ if key not in props and key not in reserved_props:
449
455
  self.errors.append(f"Additional property '{key}' not allowed at {path}")
450
456
  elif isinstance(addl, dict):
451
457
  for key in instance.keys():
452
- if key not in props:
458
+ if key not in props and key not in reserved_props:
453
459
  self.validate_instance(instance[key], addl, f"{path}/{key}")
454
460
  # Extended object constraint: "has" keyword. [Metaschema: ObjectValidationAddIn]
455
461
  if "has" in schema:
@@ -599,7 +605,13 @@ class JSONStructureInstanceValidator:
599
605
  def validate(self, instance, schema=None):
600
606
  if schema is None:
601
607
  schema = self.root_schema
602
- errors = []
608
+
609
+ # First, run the core validation (handles $root, types, required, etc.)
610
+ # Pass None for schema to trigger $root handling if this is the root schema
611
+ self.errors = []
612
+ self.validate_instance(instance, None if schema is self.root_schema else schema, "#")
613
+ errors = list(self.errors)
614
+
603
615
  # Extended: conditional composition
604
616
  if self.extended and "JSONStructureConditionalComposition" in self.enabled_extensions:
605
617
  for key in ("allOf", "anyOf", "oneOf"):
@@ -1166,25 +1178,69 @@ class JSONStructureInstanceValidator:
1166
1178
 
1167
1179
 
1168
1180
  def main():
1181
+ """Command line entry point for validating JSON instances against JSON Structure schemas."""
1169
1182
  import argparse
1170
- parser = argparse.ArgumentParser()
1171
- parser.add_argument('instance_file')
1172
- parser.add_argument('schema_file')
1173
- parser.add_argument('--extended', action='store_true')
1183
+ parser = argparse.ArgumentParser(
1184
+ prog='json-structure-validate',
1185
+ description='Validate JSON instances against JSON Structure schemas.',
1186
+ epilog='Example: json-structure-validate instance.json schema.json'
1187
+ )
1188
+ parser.add_argument('instance_file', help='Path to the JSON instance file to validate')
1189
+ parser.add_argument('schema_file', help='Path to the JSON Structure schema file')
1190
+ parser.add_argument('--extended', '-e', action='store_true',
1191
+ help='Enable extended validation features (conditional composition, validation keywords)')
1192
+ parser.add_argument('--allowimport', '-i', action='store_true',
1193
+ help='Enable processing of $import and $importdefs keywords')
1194
+ parser.add_argument('--importmap', '-m', action='append', metavar='URI=FILE',
1195
+ help='Map import URI to local file (can be specified multiple times)')
1196
+ parser.add_argument('--quiet', '-q', action='store_true',
1197
+ help='Only output errors, suppress success message')
1174
1198
  args = parser.parse_args()
1175
- import json
1176
- with open(args.schema_file, 'r', encoding='utf-8') as f:
1177
- schema = json.load(f)
1178
- with open(args.instance_file, 'r', encoding='utf-8') as f:
1179
- instance = json.load(f)
1180
- validator = JSONStructureInstanceValidator(schema, extended=args.extended)
1199
+
1200
+ # Build import map from arguments
1201
+ import_map = {}
1202
+ if args.importmap:
1203
+ for mapping in args.importmap:
1204
+ if '=' not in mapping:
1205
+ print(f"Error: Invalid --importmap format '{mapping}'. Expected URI=FILE")
1206
+ sys.exit(1)
1207
+ uri, filename = mapping.split('=', 1)
1208
+ import_map[uri] = filename
1209
+
1210
+ try:
1211
+ with open(args.schema_file, 'r', encoding='utf-8') as f:
1212
+ schema = json.load(f)
1213
+ except FileNotFoundError:
1214
+ print(f"Error: Schema file not found: {args.schema_file}")
1215
+ sys.exit(1)
1216
+ except json.JSONDecodeError as ex:
1217
+ print(f"Error: Invalid JSON in schema file: {ex}")
1218
+ sys.exit(1)
1219
+
1220
+ try:
1221
+ with open(args.instance_file, 'r', encoding='utf-8') as f:
1222
+ instance = json.load(f)
1223
+ except FileNotFoundError:
1224
+ print(f"Error: Instance file not found: {args.instance_file}")
1225
+ sys.exit(1)
1226
+ except json.JSONDecodeError as ex:
1227
+ print(f"Error: Invalid JSON in instance file: {ex}")
1228
+ sys.exit(1)
1229
+
1230
+ validator = JSONStructureInstanceValidator(
1231
+ schema,
1232
+ allow_import=args.allowimport,
1233
+ import_map=import_map,
1234
+ extended=args.extended
1235
+ )
1181
1236
  errors = validator.validate(instance)
1182
1237
  if errors:
1183
1238
  print("Instance is invalid:")
1184
1239
  for err in errors:
1185
1240
  print(" -", err)
1186
- exit(1)
1187
- print("Instance is valid.")
1241
+ sys.exit(1)
1242
+ if not args.quiet:
1243
+ print("Instance is valid.")
1188
1244
 
1189
1245
 
1190
1246
  if __name__ == "__main__":
@@ -1,4 +1,8 @@
1
1
  # encoding: utf-8
2
+ # Suppress the runpy module import warning when running as python -m
3
+ import warnings
4
+ warnings.filterwarnings("ignore", message="'json_structure.*' found in sys.modules")
5
+
2
6
  """
3
7
  json_structure_schema_validator.py
4
8
 
@@ -990,65 +994,61 @@ def validate_json_structure_schema_core(schema_document, source_text=None, allow
990
994
 
991
995
 
992
996
  def main():
993
- """
994
- Command line entry point.
995
- Expects [--metaschema] [--allowimport] [--extended] [--importmap URI=filename ...] and <path_to_json_file> as arguments.
996
- Prints errors with line and column information if found, otherwise prints "Schema is valid."
997
- """
998
- args = sys.argv[1:]
999
- allow_dollar = False
1000
- allow_import = False
1001
- extended = False
1002
- import_map = {}
997
+ """Command line entry point for validating JSON Structure schema files."""
998
+ import argparse
999
+ parser = argparse.ArgumentParser(
1000
+ prog='json-structure-check',
1001
+ description='Validate JSON Structure schema files for conformance with the specification.',
1002
+ epilog='Example: json-structure-check schema.json'
1003
+ )
1004
+ parser.add_argument('schema_file', help='Path to the JSON Structure schema file to validate')
1005
+ parser.add_argument('--metaschema', action='store_true',
1006
+ help="Allow '$' in property names (for validating metaschemas)")
1007
+ parser.add_argument('--extended', '-e', action='store_true',
1008
+ help='Enable extended validation features (conditional composition, validation keywords)')
1009
+ parser.add_argument('--allowimport', '-i', action='store_true',
1010
+ help='Enable processing of $import and $importdefs keywords')
1011
+ parser.add_argument('--importmap', '-m', action='append', metavar='URI=FILE',
1012
+ help='Map import URI to local file (can be specified multiple times)')
1013
+ parser.add_argument('--quiet', '-q', action='store_true',
1014
+ help='Only output errors, suppress success message')
1015
+ args = parser.parse_args()
1003
1016
 
1004
- # Process flags.
1005
- while args and args[0].startswith("--"):
1006
- arg = args.pop(0)
1007
- if arg == "--metaschema":
1008
- allow_dollar = True
1009
- elif arg == "--allowimport":
1010
- allow_import = True
1011
- elif arg == "--extended":
1012
- extended = True
1013
- elif arg.startswith("--importmap"):
1014
- if "=" in arg:
1015
- _, mapping_str = arg.split("--importmap=", 1)
1016
- else:
1017
- if not args:
1018
- print("Missing value for --importmap")
1019
- sys.exit(1)
1020
- mapping_str = args.pop(0)
1021
- parts = mapping_str.split("=", 1)
1022
- if len(parts) != 2:
1023
- print("Invalid --importmap format. Expected format: URI=filename")
1017
+ # Build import map from arguments
1018
+ import_map = {}
1019
+ if args.importmap:
1020
+ for mapping in args.importmap:
1021
+ if '=' not in mapping:
1022
+ print(f"Error: Invalid --importmap format '{mapping}'. Expected URI=FILE")
1024
1023
  sys.exit(1)
1025
- uri, filename = parts
1024
+ uri, filename = mapping.split('=', 1)
1026
1025
  import_map[uri] = filename
1027
- else:
1028
- print(f"Unknown flag {arg}")
1029
- sys.exit(1)
1030
1026
 
1031
- if len(args) < 1:
1032
- print("Usage: python json_structure_schema_validator.py [--metaschema] [--allowimport] [--extended] [--importmap URI=filename ...] <path_to_json_file>")
1033
- sys.exit(1)
1034
- file_path = args[0]
1035
1027
  try:
1036
- with open(file_path, "r", encoding="utf-8") as file_in:
1028
+ with open(args.schema_file, "r", encoding="utf-8") as file_in:
1037
1029
  source_text = file_in.read()
1038
1030
  data = json.loads(source_text)
1039
- except (FileNotFoundError, json.JSONDecodeError) as ex:
1040
- if hasattr(ex, 'lineno') and hasattr(ex, 'colno'):
1041
- print(f"Error reading JSON file: {ex.msg} (Line: {ex.lineno}, Column: {ex.colno})")
1042
- else:
1043
- print(f"Error reading JSON file: {ex}")
1031
+ except FileNotFoundError:
1032
+ print(f"Error: Schema file not found: {args.schema_file}")
1044
1033
  sys.exit(1)
1045
- errors = validate_json_structure_schema_core(data, source_text, allow_dollar=allow_dollar, allow_import=allow_import, import_map=import_map, extended=extended)
1034
+ except json.JSONDecodeError as ex:
1035
+ print(f"Error: Invalid JSON in schema file: {ex.msg} (Line: {ex.lineno}, Column: {ex.colno})")
1036
+ sys.exit(1)
1037
+
1038
+ errors = validate_json_structure_schema_core(
1039
+ data, source_text,
1040
+ allow_dollar=args.metaschema,
1041
+ allow_import=args.allowimport,
1042
+ import_map=import_map,
1043
+ extended=args.extended
1044
+ )
1046
1045
  if errors:
1047
1046
  print("Schema is invalid:")
1048
1047
  for err in errors:
1049
1048
  print(" -", err)
1050
1049
  sys.exit(1)
1051
- print("Schema is valid.")
1050
+ if not args.quiet:
1051
+ print("Schema is valid.")
1052
1052
 
1053
1053
 
1054
1054
  if __name__ == "__main__":