如何将Python dict树化?

2024-03-29 15:59:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个telegram机器人,并希望转换json响应,例如下面的一个,我将其转换为一个字典:

{
  "message_id": 445793,
  "from": {
   "id": 106596774,
   "is_bot": false,
   "first_name": "Komron",
   "last_name": "Aripov",
   "username": "tgcode",
   "language_code": "en"
  },
  "chat": {
   "id": 106596774,
   "first_name": "Komron",
   "last_name": "Aripov",
   "username": "tgcode",
   "type": "private"
  },
  "date": 1549380586,
  "text": "ayye"
}

变成一棵整齐的小树,例如:

Message
 ├ message_id: 445793
 ├ from
 ┊  ├ id: 106596774
 ┊  ├ is_bot: false
 ┊  ├ first_name: Komron
 ┊  ├ last_name: Aripov
 ┊  ├ username: tgcode
 ┊  └ language_code: en
 ├ chat
 ┊  ├ id: 106596774
 ┊  ├ first_name: Komron
 ┊  ├ last_name: Aripov
 ┊  ├ username: tgcode
 ┊  └ type: private
 ├ date: 1549290736
 └ text: ayye

我尝试过使用python的treelib库,但它没有为类提供将json转换为所需格式文本的方法。对于我的用例来说,它似乎有点太复杂了。你知道吗

github上有一个用于我的用例的库,但它是用javascript编写的(不能理解为逆向工程)


Tags: namefromidjsonfalsemessageisbot
1条回答
网友
1楼 · 发布于 2024-03-29 15:59:45

这看起来很有趣,所以我试了一下:

def custom_display(input, depth = 0):
    if depth == 0:
        output_string = "Message\n"
    else:
        output_string = ""
    if type(input) is dict:
        final_index = len(input)-1
        current_index = 0
        for key, value in input.items():
            for indent in range(0, depth):
                output_string += "  ┊ "
            if current_index == final_index:
                output_string += "  └ "
            else:
                output_string += "  ├ "
                current_index += 1
            if type(value) is dict:
                output_string += key + '\n' + custom_display(value, depth + 1)
            else:
                output_string += key + ": " + custom_display(value, depth+1) + '\n'
    else:
        output_string = str(input)

    return output_string

使用

dict_input = {
  "message_id": 445793,
  "from": {
   "id": 106596774,
   "is_bot": False,
   "first_name": "Komron",
   "last_name": "Aripov",
   "username": "tgcode",
   "language_code": "en"
  },
  "chat": {
   "id": 106596774,
   "first_name": "Komron",
   "last_name": "Aripov",
   "username": "tgcode",
   "type": "private"
  },
  "date": 1549380586,
  "text": "ayye"
}

print(custom_display(dict_input))

输出:

Message
  ├ message_id: 445793
  ├ from
  ┊   ├ id: 106596774
  ┊   ├ is_bot: False
  ┊   ├ first_name: Komron
  ┊   ├ last_name: Aripov
  ┊   ├ username: tgcode
  ┊   └ language_code: en
  ├ chat
  ┊   ├ id: 106596774
  ┊   ├ first_name: Komron
  ┊   ├ last_name: Aripov
  ┊   ├ username: tgcode
  ┊   └ type: private
  ├ date: 1549380586
  └ text: ayye

相关问题 更多 >