File size: 2,200 Bytes
ab4488b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import json

from .dictexporter import DictExporter


class JsonExporter:
    """
    Tree to JSON exporter.

    The tree is converted to a dictionary via `dictexporter` and exported to JSON.

    Keyword Arguments:
        dictexporter: Dictionary Exporter used (see :any:`DictExporter`).
        maxlevel (int): Limit export to this number of levels.
        kwargs: All other arguments are passed to
                :any:`json.dump`/:any:`json.dumps`.
                See documentation for reference.

    >>> from anytree import AnyNode
    >>> from anytree.exporter import JsonExporter
    >>> root = AnyNode(a="root")
    >>> s0 = AnyNode(a="sub0", parent=root)
    >>> s0a = AnyNode(a="sub0A", b="foo", parent=s0)
    >>> s0b = AnyNode(a="sub0B", parent=s0)
    >>> s1 = AnyNode(a="sub1", parent=root)

    >>> exporter = JsonExporter(indent=2, sort_keys=True)
    >>> print(exporter.export(root))
    {
      "a": "root",
      "children": [
        {
          "a": "sub0",
          "children": [
            {
              "a": "sub0A",
              "b": "foo"
            },
            {
              "a": "sub0B"
            }
          ]
        },
        {
          "a": "sub1"
        }
      ]
    }

    .. note:: Whenever the json output does not meet your expections, see the :any:`json` documentation.
              For instance, if you have unicode/ascii issues, please try `JsonExporter(..., ensure_ascii=False)`.
    """

    def __init__(self, dictexporter=None, maxlevel=None, **kwargs):
        self.dictexporter = dictexporter
        self.maxlevel = maxlevel
        self.kwargs = kwargs

    def _export(self, node):
        dictexporter = self.dictexporter or DictExporter()
        if self.maxlevel is not None:
            dictexporter.maxlevel = self.maxlevel
        return dictexporter.export(node)

    def export(self, node):
        """Return JSON for tree starting at `node`."""
        data = self._export(node)
        return json.dumps(data, **self.kwargs)

    def write(self, node, filehandle):
        """Write JSON to `filehandle` starting at `node`."""
        data = self._export(node)
        return json.dump(data, filehandle, **self.kwargs)