Schema for type tagged data

139 views
Skip to first unread message

jonas....@gmail.com

unread,
Feb 10, 2015, 2:23:24 AM2/10/15
to json-...@googlegroups.com
Hi!

What is the best approach to describing data with type tags? (Or, alternatively, how to structure the data in such a way that type tags are not needed at all)

Example:


  {“type”: “login”,
   “username”: “foo”,
   “timestamp”: 342123}


  {“type”: “forgotPassword”,
   “email”: “f...@example.com”,
   “timestamp”: 423421}

The following approach is the best I’ve found:


Main schema:
  
  {“oneOf”: [{“$ref”: “login-event.json”},
                  {“$ref”: “forgot-password-event.json”}]}

login-event.json:

  {“type”: “object”,
   “properties”: {“type”: {“enum”: [“login”]},
                         “email”: {“type”: “string”},
                         “timestamp”: {“type: “number”}}}

forgot-password-event.json would of course look similar.

Is there a better way to create schemas for type tagged data (where the value of the type property determines the structure of the rest of the object)? Is it possible specify common properties (for example "timestamp" in the example) in the top level schema instead of in each sub schema? 

I’ve also found that validation failure reports are extremely verbose when the top level schema is a long list of “oneOf” schemas.

Thanks,
Jonas

Austin Wright

unread,
Feb 11, 2015, 2:20:12 AM2/11/15
to json-...@googlegroups.com, jonas....@gmail.com
"oneOf" with "enum" is the only way I know of to do that.

Maybe we could do something similar to the "dependencies" property, but for property values... I don't even know how that would look, though.

Which validator are you using?

Austin Wright.

jonas....@gmail.com

unread,
Feb 11, 2015, 2:39:21 AM2/11/15
to json-...@googlegroups.com, jonas....@gmail.com
Hi Austin

Thanks for your reply. I suspected it was the only way to go (since a similar approach is used in the advanced example at http://json-schema.org/example2.html) but I wanted to ask just to make sure.

Ari Okkonen

unread,
Sep 1, 2020, 11:01:54 AM9/1/20
to JSON Schema
It seems that a way to define a tagged (or discriminated) union is needed. I use such in my system but cannot validate it strictly using Json schema. In tagged union the names, types, and other restrictions of other fields of an object depend on an enumerated value of the tag (discriminant) field.  https://en.wikipedia.org/wiki/Tagged_union .
Example of problematic data:
  [
    {"t":"move","id":"2780","x":758.32,"y":334.28},
    {"t":"msg","id":3354,"data":"2A7F4A42B9022"},
    {"t":"move","id":"3354","x":433.15,"y":248.13}
  ]


Reply all
Reply to author
Forward
0 new messages