Requirement: In the wave of AI large model era, various industries are adopting AI to help us analyze data. Some are called through programming languages. We want AI large models to output JSON-structured data. How can we verify whether the JSON strings output by AI models match the types defined by our object-oriented approach?
JsonSchema.Net
Sometimes you may need to verify that the JSON object is properly formatted (with the correct key and value types), or you may want to add comments to the data. This is where JSON Schema comes in handy. Similar to XML Schema, JSON Schema defines a pattern for JSON data. The JSON Schema validator can verify whether a given JSON object meets the requirements defined by the JSON Schema and provides the application with additional information about the data. This evaluation can serve as a preparatory step before deserialization and is very useful.
Source:The hyperlink login is visible. Documentation:The hyperlink login is visible.
Currently, six versions of the JSON Schema specification are known:
- Draft 3
- Draft 4
- Draft 6
- Draft 7
- Draft 2019-09
- Draft 2020-12
The JSON Schema team recommends using Draft 7 or 2020-12. JsonSchema.Net support Draft 6 and later.
Basic tutorial
We define an object for a person, then generate a schema. The code is as follows:
The output is as follows:
{ "type": [ "object", "null" ], "properties": { "Name": { "type": [ "string", "null" ] }, "Email": { "type": [ "string", "null" ] }, "Age": { "type": "integer" }, "Address": { "type": [ "array", "null" ], "items": { "type": [ "object", "null" ], "properties": { "Location": { "type": [ "string", "null" ] }, "ZipCode": { "type": "integer" } }, "required": [ "Location", "ZipCode" ] } } }, "required": [ "Name", "Email", "Age", "Address" ]
} Use JsonSchema to verify whether a JSON string conforms to the object structure. The code is as follows:
As shown below:
Using the builder pattern, the code is as follows:
(End) |