json-schema: how to transform from one json-schema to another

假如想象 提交于 2019-12-05 14:03:49

This is not something that JSON Schema is designed for. Transforming JSON from one JSON Schema to another requires a human to provide context for the transformation.

For example, here is a fairly simple transformation for a human to do.

jsonA

{
  "key1": "value1",
  "key2": "value2"
}

schemaA

{
  "type": "object",
  "additionalProperties": {
    "type": "string"
  }
}

schemaB

{
  "type": "array",
  "items": {
    "type": "array",
    "items": [
      { "type": "string" },
      { "type": "string" }
    ]
  }
}

Can you figure out what the transformation should be from this information alone? Maybe, but there are too many ambiguities for it to be done problematically. This transformation converts an object to an array of key/value pairs.

jsonB

[
  ["key1", "value1"],
  ["key2", "value2"]
]

Because of the ambiguity comparing schemas, just about any transformations will have to be done manually on a case-by-case basis. I don't think you will get very far with this approach.

JSON-LD

You might want to look into JSON-LD as an alternative. A JSON-LD document describes data as a directed graph. Consequently, there are multiple ways a JSON-LD document can be expressed as a JSON object. In JSON-LD, this is called framing.

The idea would be to describe your calendar as a JSON-LD document that can be framed to match either schemaA or schemaB. To put it another way, the JSON-LD document is the context needed to remove the ambiguities between the schemas. I would show an example, but I don't know JSON-LD that well. I'll leave it to you it look into it if you think it might solve your problem.

I believe a library like this could be used to address your question. This does not directly address the question (transforming from one JSON schema to the other) but what you can do (which is what I am currently doing) is the following:

  1. Specify a JSON schema for your input
  2. Specify a JSON schema for your output
  3. Specify a mapping template (e.g. using the library I referenced).

Of course, ideally you would not have to do both 2 and 3 but I have not found something which does this automatically. So, for example, you could specify the mapping template and create some library function which takes that as well as the JSON schema in 1 as its inputs, and would generate the JSON schema in 3 as its output.

This, however, is not trivial so currently I am specifying both 2 and 3.

Also, keep in mind that you cannot have 1 and 2 and somehow automatically generate 3. This is because there are more than one mapping functions that would take data adhering to schema 1 and produce data adhering to schema 2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!