File size: 1,777 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 |
# -*- coding: utf-8 -*-
import json
from .dictimporter import DictImporter
class JsonImporter:
"""
Import Tree from JSON.
The JSON is read and converted to a dictionary via `dictimporter`.
Keyword Arguments:
dictimporter: Dictionary Importer used (see :any:`DictImporter`).
kwargs: All other arguments are passed to
:any:`json.load`/:any:`json.loads`.
See documentation for reference.
>>> from anytree.importer import JsonImporter
>>> from anytree import RenderTree
>>> importer = JsonImporter()
>>> data = '''
... {
... "a": "root",
... "children": [
... {
... "a": "sub0",
... "children": [
... {
... "a": "sub0A",
... "b": "foo"
... },
... {
... "a": "sub0B"
... }
... ]
... },
... {
... "a": "sub1"
... }
... ]
... }'''
>>> root = importer.import_(data)
>>> print(RenderTree(root))
AnyNode(a='root')
βββ AnyNode(a='sub0')
β βββ AnyNode(a='sub0A', b='foo')
β βββ AnyNode(a='sub0B')
βββ AnyNode(a='sub1')
"""
def __init__(self, dictimporter=None, **kwargs):
self.dictimporter = dictimporter
self.kwargs = kwargs
def __import(self, data):
dictimporter = self.dictimporter or DictImporter()
return dictimporter.import_(data)
def import_(self, data):
"""Read JSON from `data`."""
return self.__import(json.loads(data, **self.kwargs))
def read(self, filehandle):
"""Read JSON from `filehandle`."""
return self.__import(json.load(filehandle, **self.kwargs))
|