代码之家  ›  专栏  ›  技术社区  ›  Alihossein shahabi

如何在python中将telethon对象转换为有效的JSON

  •  0
  • Alihossein shahabi  · 技术社区  · 7 年前

    我使用telethon软件包,用于连接和从电报中获取数据。 我想将消息对象转换为有效的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"
    }}
    

    2 回复  |  直到 7 年前
        1
  •  1
  •   Alihossein shahabi    7 年前

    我这样解决了我的问题

    我希望它对你也有用

    例如,我得到 channel

    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")
    
        2
  •  1
  •   Aleksandr L    4 年前

    例如,您可以递归地将每个对象转换为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)