JSON Schema中与XML的targetNamespace等效的机制是什么?
targetNamespace Great question! Let's start by grounding this in what we know about XML Schema first: targetNamespace gives all components defined in an XSD a clear, unique "home" namespace—this prevents naming collisions between schemas and lets other documents/schemas reference those components unambiguously.
In JSON Schema, the closest equivalent (and core mechanism for this purpose) is the $id keyword. Here's how it maps to targetNamespace's role, plus some context specific to JSON:
Unique Identifier as "Namespace":
$iddefines a unique URI (can be a URL or a relative path) for your JSON Schema. This URI acts like a namespace: it uniquely identifies all the structures (objects, properties, etc.) defined in that schema. Just liketargetNamespacein XSD, it ensures that a "User" object defined in one schema doesn't get confused with a "User" defined in another.Enabling Cross-Schema References:
When you need to reference a definition from another schema, you use the$refkeyword combined with the target schema's$idURI. This works exactly like how you'd reference XSD components using theirtargetNamespace—it tells validators exactly where to find the correct definition.Bonus: Internal Schema References:
Beyond just acting as a namespace anchor,$idalso lets you set up relative references within the same schema. For example, if you have a reusableAddressdefinition in your schema, you can reference it with#/definitions/Addresswhere the#is relative to the$idURI.
Example to Make It Concrete
Let's say we have a user schema with a clear $id (our "namespace"):
{ "$id": "https://myapp.com/schemas/user", "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "userId": {"type": "string"}, "fullName": {"type": "string"} }, "required": ["userId", "fullName"] }
Then, an order schema can reference this user definition using the $id URI:
{ "$id": "https://myapp.com/schemas/order", "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "orderId": {"type": "string"}, "customer": {"$ref": "https://myapp.com/schemas/user"} }, "required": ["orderId", "customer"] }
A quick note to avoid confusion: the $schema keyword (used in both examples) is just for specifying which version of the JSON Schema standard your schema follows—it's not related to targetNamespace. The $id is the real equivalent here.
内容的提问来源于stack exchange,提问作者LudvigH

