Viewing Models as JSON¶
Models generated by 竜 TatSu can be viewed by converting them to a JSON-compatible structure
with the help of tatsu.util.asjson()
. The protocol tries to provide the best
representation for common types, and can handle any type using repr()
. There are provisions for structures with back-references, so there’s no infinite recursion.
import json
print(json.dumps(asjson(model), indent=2))
The model
, with richer semantics, remains unaltered.
Conversion to a JSON-compatible structure relies on the protocol defined by
tatsu.utils.AsJSONMixin
. The mixin defines a __json__(seen=None)
method that allows classes to define their best translation. You can use AsJSONMixin
as a base class in your own models to take advantage of asjson()
, and you can
specialize the conversion by overriding AsJSONMixin.__json__()
.
You can also write your own version of asjson()
to handle special cases that are recurrent in your context.