簡體   English   中英

如何在python中將telethon對象轉換為有效的JSON

[英]how to convert telethon object to valid JSON in python

我使用 Telethon 包,用於連接和從電報中獲取數據。 我想將 Message 對象轉換為有效的 JSON。 例如,我從 Telethon 中的一個 API 獲取此對象:

{
Message: {
    via_bot_id: None,
    entities: [],
    out: None,
    post: True,
    from_id: None,
    message: "hi everybody",
    id: 71,
    media_unread: None,
    reply_markup: None,
    fwd_from: {
        channel_id: 1119999790,
        channel_post: 2,
        date: 2017 - 09 - 04 15: 43: 48,
        from_id: None
    },
    reply_to_msg_id: None,
    edit_date: None,
    to_id: {
        channel_id: 1099583379
    },
    views: 2,
    mentioned: None,
    date: 2017 - 09 - 05 09: 28: 46,
    media: None,
    silent: None
} }

這是我最喜歡的結果:

{
"Message": {
    "via_bot_id": "None",
    "entities": [],
    "out": "None",
    "post": "True",
    "from_id": "None",
    "message": "hi everybody",
    "id": 71,
    "media_unread": "None",
    "reply_markup": "None",
    "fwd_from": {
        "channel_id": 1119999790,
        "channel_post": 2,
        "date": "2017 - 09 - 04 15: 43: 48",
        "from_id": "None"
    },
    "reply_to_msg_id": "None",
    "edit_date": "None",
    "to_id": {
        "channel_id": 1099583379
    },
    "views": 2,
    "mentioned": "None",
    "date": "2017 - 09 - 05 09: 28: 46",
    "media": "None",
    "silent": "None"
}}

有沒有辦法在 Python 中進行轉換?

例如,您可以將每個對象遞歸地轉換為 dict:

def has_to_dict(obj):
   method = getattr(obj, "to_dict", None)

   return callable(method)

def to_dict_req(obj):
res = {}
if has_to_dict(obj):
    for key, value in obj.to_dict().items():
        if has_to_dict(value):
            value = to_dict_req(value)
        else:
            value = str(value)
        res[key] = value
    return res
else:
    return str(obj)

我這樣解決了我的問題

我希望它對你也有用

例如,我獲取channel對象並將其轉換為 JSON。

index.py

import json

from telethon import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.types import ChannelParticipantsSearch

from helpers import date_format

api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXXXXX'
################################################
channel_username = 'tehrandb'
################################################

client = TelegramClient('session_name',
                    api_id,
                    api_hash)

assert client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
me = client.sign_in(phone_number, input('Enter code: '))

# ---------------------------------------
my_filter = ChannelParticipantsSearch('')
all_participants = []
while_condition = True
# ---------------------------------------
channel = client(GetFullChannelRequest(channel_username))
channel_dict = channel.to_dict()
json = json.dumps(channel_dict,default=date_format)

helpers.py

import datetime


def date_format(message):
    """
    :param message:
    :return:
    """
    if type(message) is datetime:
        return message.strftime("%Y-%m-%d %H:%M:%S")

暫無
暫無

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

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