如何在Python中将Json对象转换为树类型?

时间:2019-04-03 07:25:06

标签: python json

我有以下Json:

 { 
   file1: {
     path_to_file: 'file1.txt',
     children : 'file2'
   },
   file2: {
     path_to_file: 'file1.txt',
     children : 'file3,file4'
   },
   file3: {
     path_to_file: 'a/file3.txt',
     children : ''
   },
   file4: {
     path_to_file: 'b/file4.txt',
     children : ''
   }
 }

我想从这个Json构造一棵树。 每个节点都应具有:名称(file1等),path_to_file(仅是数据字段),并将子级转换为指向下一个节点的“指针”。

我有以下代码:

class Node(object):
    def __init__(self, name, path_to_file=None):
        self.name = name
        self.path_to_file= path_to_file
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

这可以用作:

>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)

现在,我想使用json中的属性,而不是上面的数字。所以我有这段代码:

jsonObject= json.load(json_string)
for key in jsonObject:
   value = jsonObject[key]
   print("The key and value are ({}) = ({})".format(key, value))

这给了我

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 4 (char 7)

如何构造Json对象中的属性以构造对Node类的调用?

1 个答案:

答案 0 :(得分:1)

您的json不是标准的json格式,应该为双引号,没有单引号

import json

json_string = """
{
    "file1": {
        "path_to_file": "file1.txt",
        "children": "file2"
    },
    "file2": {
        "path_to_file": "file1.txt",
        "children": "file3,file4"
    },
    "file3": {
        "path_to_file": "a/file3.txt",
        "children": ""
    },
    "file4": {
        "path_to_file": "b/file4.txt",
        "children": ""
    }
}
"""

jsonObject = json.loads(json_string)
for key in jsonObject:
   value = jsonObject[key]
   print("The key and value are ({}) = ({})".format(key, value))

输出为:

The key and value are (file1) = ({'path_to_file': 'file1.txt', 'children': 'file2'})
The key and value are (file2) = ({'path_to_file': 'file1.txt', 'children': 'file3,file4'})
The key and value are (file3) = ({'path_to_file': 'a/file3.txt', 'children': ''})
The key and value are (file4) = ({'path_to_file': 'b/file4.txt', 'children': ''})

更新答案

为了更好地显示,我添加了转储方法。

import json
json_string = """
{
    "file1": {
        "path_to_file": "file1.txt",
        "children": "file2"
    },
    "file2": {
        "path_to_file": "file1.txt",
        "children": "file3,file4"
    },
    "file3": {
        "path_to_file": "a/file3.txt",
        "children": ""
    },
    "file4": {
        "path_to_file": "b/file4.txt",
        "children": ""
    }
}
"""


class Node(object):
    def __init__(self, name, path_to_file=None):
        self.name = name
        self.path_to_file = path_to_file
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

    def dump(self, indent=0):
        """dump tree to string"""
        tab = '    '*(indent-1) + ' |- ' if indent > 0 else ''
        print('%s%s' % (tab, self.name))
        for obj in self.children:
            obj.dump(indent + 1)


name2info = json.loads(json_string)


def get_tree(name):
    info = name2info[name]
    root = Node(name, info['path_to_file'])
    for child in info['children'].split(","):
        if child:
            root.add_child(get_tree(child))
    return root


root = get_tree('file1')

# get children info
print(root.name, root.children[0].name, root.children[0].children[1].path_to_file)

root.dump()

它输出:

file1 file2 b/file4.txt
file1
 |- file2
     |- file3
     |- file4