使用fastjsonschema编译含引用JSON Schema遇TypeError错误求助
Let's break down and fix the issues you're facing step by step:
1. Immediate Cause: Passing JSON String Instead of Parsed Dictionary
The TypeError: string indices must be integers happens because fastjsonschema.compile() expects a Python dictionary (parsed JSON data), but you’re passing a raw JSON string. When the library tries to traverse the schema (like checking for $ref entries), it treats the string as a sequence and tries to index it with strings—hence the error.
Fix the Code
Update your code to parse the JSON file directly into a Python dictionary using json.load():
import fastjsonschema import json # Use a context manager to safely handle file operations with open("schema.json") as schema_file: schema = json.load(schema_file) # Parses file content into a dict # Now compile the properly structured schema validation = fastjsonschema.compile(schema)
2. Hidden Schema Structure Error
Even after fixing the code, your schema has a structural mistake that would break validation. In the definitions.organization section, you incorrectly nested the required and additionalProperties fields inside the properties object. These are top-level constraints for the organization object and must sit at the same level as properties.
Fix the Schema
Here’s the corrected schema.json:
{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "organization", "description": "JSON schema", "type": "object", "properties": { "transactionDetail": { "id": "https://example.com/transactionDetail", "type": "object", "properties": { "transactionID": { "description": "A number assigned by the calling application to uniquely identify this request.", "type": "string" }, "transactionTimestamp": { "description": "The date and time when this request was submitted.", "type": "string" } }, "required": [ "transactionID" ], "additionalProperties": false }, "organization": { "$ref": "#/definitions/organization" } }, "additionalProperties": false, "definitions": { "organization": { "type": "object", "properties": { "identifier": { "description": "identification number.", "type": "string", "minLength": 1, "maxLength": 12 }, "countryCode": { "description": "The two-letter country code.", "type": "string", "minLength": 2, "maxLength": 2 }, "timestamp": { "description": "The date and time that the record was created.", "type": "string" } }, "required": [ "identifier", "countryCode" ], "additionalProperties": false } } }
Why This Works
- Parsing the JSON into a dictionary gives
fastjsonschemathe structured data it needs to traverse and compile the schema without treating strings as indexable sequences. - Moving
requiredandadditionalPropertiesto the correct level ensures the schema adheres to JSON Schema Draft 04 rules, allowing reference resolution to function as expected.
After applying both fixes, you should be able to compile the schema without errors.
内容的提问来源于stack exchange,提问作者Sumit Bharati

