簡體   English   中英

如何在python中將Json對象轉換為樹類型?

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

我有以下 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 類的調用?

你的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM