jsonexporter.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import json
  2. from .dictexporter import DictExporter
  3. class JsonExporter(object):
  4. def __init__(self, dictexporter=None, maxlevel=None, **kwargs):
  5. """
  6. Tree to JSON exporter.
  7. The tree is converted to a dictionary via `dictexporter` and exported to JSON.
  8. Keyword Arguments:
  9. dictexporter: Dictionary Exporter used (see :any:`DictExporter`).
  10. maxlevel (int): Limit export to this number of levels.
  11. kwargs: All other arguments are passed to
  12. :any:`json.dump`/:any:`json.dumps`.
  13. See documentation for reference.
  14. >>> from anytree import AnyNode
  15. >>> from anytree.exporter import JsonExporter
  16. >>> root = AnyNode(a="root")
  17. >>> s0 = AnyNode(a="sub0", parent=root)
  18. >>> s0a = AnyNode(a="sub0A", b="foo", parent=s0)
  19. >>> s0b = AnyNode(a="sub0B", parent=s0)
  20. >>> s1 = AnyNode(a="sub1", parent=root)
  21. >>> exporter = JsonExporter(indent=2, sort_keys=True)
  22. >>> print(exporter.export(root))
  23. {
  24. "a": "root",
  25. "children": [
  26. {
  27. "a": "sub0",
  28. "children": [
  29. {
  30. "a": "sub0A",
  31. "b": "foo"
  32. },
  33. {
  34. "a": "sub0B"
  35. }
  36. ]
  37. },
  38. {
  39. "a": "sub1"
  40. }
  41. ]
  42. }
  43. .. note:: Whenever the json output does not meet your expections, see the :any:`json` documentation.
  44. For instance, if you have unicode/ascii issues, please try `JsonExporter(..., ensure_ascii=False)`.
  45. """
  46. self.dictexporter = dictexporter
  47. self.maxlevel = maxlevel
  48. self.kwargs = kwargs
  49. def _export(self, node):
  50. dictexporter = self.dictexporter or DictExporter()
  51. if self.maxlevel is not None:
  52. dictexporter.maxlevel = self.maxlevel
  53. return dictexporter.export(node)
  54. def export(self, node):
  55. """Return JSON for tree starting at `node`."""
  56. data = self._export(node)
  57. return json.dumps(data, **self.kwargs)
  58. def write(self, node, filehandle):
  59. """Write JSON to `filehandle` starting at `node`."""
  60. data = self._export(node)
  61. return json.dump(data, filehandle, **self.kwargs)