Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release 5.10.0 - fixes and optimizations to asjson() #325

Merged
merged 3 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/asjson.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.. include:: links.rst

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.

.. code:: python

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.
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ input, much like the `re`_ module does with regular expressions, or it can gener
ast
semantics
models
asjson
print_translation
translation
left_recursion
Expand Down
2 changes: 1 addition & 1 deletion tatsu/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '5.9.3b1'
__version__ = '5.10.0'
2 changes: 1 addition & 1 deletion tatsu/util/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def asjson(obj, seen=None): # pylint: disable=too-many-return-statements,too-ma
elif isinstance(obj, enum.Enum):
return asjson(obj.value)
else:
return str(obj)
return repr(obj)
finally:
# NOTE: id()s may be reused
# https://docs.python.org/3/library/functions.html#id
Expand Down
Loading