82

Does anybody know how to generate a JSON schema from a existing XML schema (XSD file)? Are there any tools available for this?

konung
  • 6,908
  • 6
  • 54
  • 79
JB Hurteaux
  • 4,428
  • 6
  • 32
  • 35
  • 5
    I think the real question, "Is it possible to make a mapping between JSON Schema and XML Schema?" is not off-topic. Perhaps the question could be reworded. – Eric Hartford Aug 15 '14 at 19:34
  • 2
    Falco Nogatz did a BSc thesis in 2013 resulting in [xsd2json](https://github.com/fnogatz/xsd2json). – supervacuo Nov 04 '14 at 18:01
  • One way is to go from XSD to Java classes and from Java classes to JSON schema. Details at https://dzone.com/articles/generating-json-schema-xsd. – koppor Jun 13 '18 at 13:25

5 Answers5

48

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

lexicore
  • 42,748
  • 17
  • 132
  • 221
  • JsonSchema is dead. Any plans to support openAPI? – Lonzak Jun 26 '18 at 15:07
  • 7
    @Lonzak No plans so far. But from the first glance on the OpenAPI spec, don't `schema` parts follow the JSON Schema spec? – lexicore Jun 26 '18 at 16:27
  • 1
    this does not work, for example, with Java 12 – codeKiller Nov 13 '19 at 10:24
  • @Lonzak JSON Schema is used by OpenAPI to describe the shape of JSON content. – Eric Hartford Mar 05 '22 at 19:48
  • @EricHartford Has been a while :-) You are [right](https://swagger.io/docs/specification/data-models/keywords/). OpenAPI is using an older draft of json schema which is still in its draft phase today (2022)... – Lonzak Mar 07 '22 at 07:57
  • I've got this error: `Exception in thread "main" java.lang.NoClassDefFoundError: javax/activation/DataSource` ubuntu20.04, java version: 11.0.17, my installation: 1. `sudo apt install default-jre` 2. `npm install jsonix-schema-compiler` downloaded purchaseorder.xsd command to run: `java -jar ./node_modules/jsonix-schema-compiler/lib/jsonix-schema-compiler-full.jar -generateJsonSchema -p PO purchaseorder.xsd` – akpp Jan 26 '23 at 11:45
12

JSON Schema is not intended to be feature equivalent with XML Schema. There are features in one but not in the other.

In general you can create a mapping from XML to JSON and back again, but that is not the case for XML schema and JSON schema.

That said, if you have mapped a XML file to JSON, it is quite possible to craft an JSON Schema that validates that JSON in nearly the same way that the XSD validates the XML. But it isn't a direct mapping. And it is not possible to guarantee that it will validate the JSON exactly the same as the XSD validates the XML.

For this reason, and unless the two specs are made to be 100% feature compatible, migrating a validation system from XML/XSD to JSON/JSON Schema will require human intervention.

Eric Hartford
  • 16,464
  • 4
  • 33
  • 50
  • I don't understand this. Can you please give an example? – Fenil Dedhia Jul 07 '16 at 14:18
  • 5
    Let's say you have something like You could define a mapping to represent the entity in Json, for example: {"type": "man", name: 'Fred', pets: [{type: 'dog', name: 'Rex'}]} But, there is no guarantee you can build a mapping of XSD to Json Schema that matches the same set of documents – Eric Hartford Jul 08 '16 at 02:14
8

Disclaimer: I'm the author of jgeXml.

jgexml has Node.js based utility xsd2json which does a transformation between an XML schema (XSD) and a JSON schema file.

As with other options, it's not a 1:1 conversion, and you may need to hand-edit the output to improve the JSON schema validation, but it has been used to represent a complex XML schema inside an OpenAPI (swagger) definition.

A sample of the purchaseorder.xsd given in another answer is rendered as:

"PurchaseOrderType": {
  "type": "object",
  "properties": {
    "shipTo": {
      "$ref": "#/definitions/USAddress"
    },
    "billTo": {
      "$ref": "#/definitions/USAddress"
    },
    "comment": {
      "$ref": "#/definitions/comment"
    },
    "items": {
      "$ref": "#/definitions/Items"
    },
    "orderDate": {
      "type": "string",
      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}.*$"
    }
  },
MikeRalphson
  • 2,247
  • 2
  • 15
  • 16
  • I have installed it using `npm install -g jgexml`. Then `xsd2jsjon` was not in the path. I tried `node C:\Users\Oliver\AppData\Roaming\npm\node_modules\jgexml\xsd2json.js`. This, however, just returned. Is there a command line utility? – koppor Jun 13 '18 at 13:11
  • It's not intuitively named, but there is an example CLI in `testxsd2j.js` – MikeRalphson Jun 14 '18 at 09:51
  • Unfortunately it's not working, getting the error TypeError: Cannot set property 'additionalProperties' of null. (for the sake of example Jsonix worked fine with the same file) – D.Dimitrioglo Jun 16 '20 at 18:30
  • Please raise a github issue if you can share the input. – MikeRalphson Jun 17 '20 at 19:19
-1

Copy your XML schema here & get the JSON schema code to the online tools which are available to generate JSON schema from XML schema.

Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
-5

True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).

Spokk
  • 1