如何在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类的调用?

n

您的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': ''})

更新答案

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在python中将json转换为树

如何在JS中将json转换为树数组?

如何在 Python 中将 json 树数据转换为数据框?

如何在Python中将日期列从对象类型转换为日期类型

如何在Java中将对象转换为字段类型?

如何在C#中将json转换为json对象

如何在Android中将JSON包转换为JSON对象

如何在python数据框中将对象数据类型转换为浮点数

如何在python jupyter中将对象类型转换为datetime64[ns]?

如何在python中将HH.MM.SS(对象类型)列转换为HH:MM?

如何在Python中将搁置对象转换为字典对象

如何在lambda python函数中将json数组转换为json对象

如何在JavaScript中将对象键点符号转换为对象树

如何在C#中将Json对象转换为数组

如何在 api 中将 JSON 对象转换为 Typescript 数组

如何在Java中将哈希图转换为JSON对象

如何在Java中将json转换为ArrayList对象?

如何在Angular中将对象转换为JSON

如何在SwiftyJson中将文件转换为JSON对象

如何在Postgres中将查询结果转换为JSON对象

如何在Nim中将对象转换为json

如何在 JavaScript 中将纯文本转换为 Json 对象

如何在javascript中将json转换为数组对象?

如何在Swift中将Realm对象转换为JSON?

如何在Swift中将NSObject类对象转换为JSON?

如何在React Native中将JSON对象转换为数组

如何在 javascript 中将对象转换为 JSON?

如何在 python 中将 Str() 类型的列转换为数字?

在python中将返回类型转换为对象