我正在使用fastjsonschema来验证json记录基于其架构。编译方法适用于简单模式,但是在使用引用编译 json 架构时,fastjsonschema 出错。 类型错误:字符串索引必须是整数。下面是代码片段、json 架构和错误。
用于编译架构的代码 #####import fastjsonschema
schema_file = open(schema.json)
schema_str = schema_file.read()
validatation = fastjsonschema.compile(schema_str)
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
}
}
}
}
Expected Result: Nothing
Actual Result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/dnbusr1/z-gda-pad/anaconda3/lib/python3.6/site-packages/fastjsonschema/__init__.py", line 153, in compile
resolver, code_generator = _factory(definition, handlers)
File "/dnbusr1/z-gda-pad/anaconda3/lib/python3.6/site-packages/fastjsonschema/__init__.py", line 193, in _factory
resolver = RefResolver.from_schema(definition, handlers=handlers)
File "/dnbusr1/z-gda-pad/anaconda3/lib/python3.6/site-packages/fastjsonschema/ref_resolver.py", line 89, in from_schema
**kwargs
File "/dnbusr1/z-gda-pad/anaconda3/lib/python3.6/site-packages/fastjsonschema/ref_resolver.py", line 78, in __init__
self.walk(schema)
File "/dnbusr1/z-gda-pad/anaconda3/lib/python3.6/site-packages/fastjsonschema/ref_resolver.py", line 148, in walk
elif '$ref' in node and isinstance(node['$ref'], str):
TypeError: string indices must be integers
我也在为这个问题而苦苦挣扎,似乎您需要使用 dict(而不是 str(为 fastjsonschema 编译和验证方法。
轻松做到这一点的一种方法是使用 Python 中的 json 模块:
with open(myschema, 'r') as file:
schemadict = json.loads(file.read())
validate = fastjsonschema.compile(schemadict)