File: jsonparser.py

package info (click to toggle)
python-reconfigure 0.1.59%2Bgit20140824-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 708 kB
  • ctags: 692
  • sloc: python: 4,139; makefile: 181
file content (36 lines) | stat: -rw-r--r-- 1,021 bytes parent folder | download | duplicates (3)
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
from reconfigure.nodes import *
from reconfigure.parsers import BaseParser
import json


class JsonParser (BaseParser):
    """
    A parser for JSON files (using ``json`` module)
    """

    def parse(self, content):
        node = RootNode()
        self.load_node_rec(node, json.loads(content))
        return node

    def load_node_rec(self, node, json):
        for k in sorted(json.keys()):
            v = json[k]
            if isinstance(v, dict):
                child = Node(k)
                node.children.append(child)
                self.load_node_rec(child, v)
            else:
                node.children.append(PropertyNode(k, v))

    def stringify(self, tree):
        return json.dumps(self.save_node_rec(tree), indent=4)

    def save_node_rec(self, node):
        r = {}
        for child in node.children:
            if isinstance(child, PropertyNode):
                r[child.name] = child.value
            else:
                r[child.name] = self.save_node_rec(child)
        return r