简体   繁体   English

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

[英]How to convert Json object into tree type in python?

I have the following 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 : ''
   }
 }

I want to construct a tree from this Json.我想从这个 Json 构建一棵树。 each node should have: name (file1 etc..), path_to_file which is just a data field and convert the children into "pointers" to next node.每个节点都应该有:名称(file1 等),path_to_file 这只是一个数据字段,并将子节点转换为指向下一个节点的“指针”。

I have the following code:我有以下代码:

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)

This can be used as:这可以用作:

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

Now, I want to use properties from my json instead of the number above.现在,我想使用 json 中的属性而不是上面的数字。 So I have this code:所以我有这个代码:

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

This gives me:这给了我:

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

How can I extract the properties in the Json object inorder to construct the call to the Node class?如何提取 Json 对象中的属性以构造对 Node 类的调用?

Your json is not a standard json format, it should be double quotes , no single quotes你的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))

output as:输出为:

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

update answer更新答案

For better display, I added the dump method.为了更好的显示,我添加了 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()

it outputs:它输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM