亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 請求:處理 JSON 響應、存儲到列表或字典?

Python 請求:處理 JSON 響應、存儲到列表或字典?

繁星點點滴滴 2022-07-19 15:08:39
我正在使用 python 請求庫從 api 獲取數據。數據以稱為消息的大型 json 數組返回。其中包含許多單獨的“消息”子級別 jsons(請參閱底部的 json 響應示例)。在這個 json 響應中,對于每條消息,我只關心幾個(2 或 3)個數據點。我需要獲取這幾個數據點,并將它們存儲到某些東西(列表列表、字典等)中,以便以后可以引用它,存儲到一個對象并從另一個函數中使用。我需要存儲的數據點是id,conversationId和body. The id is unique, while theconversationId` 在對話中的所有消息之間共享,因此不是唯一的。我首先想問一下您認為實現這一目標的最佳方法是什么。我猜是列表列表還是列表字典?我太新了,不知道哪個是更好的解決方案。此外,無論選擇什么方法,我都需要知道如何引用它們并通過 id 調用它們以從另一個函數存儲到對象。我還沒有弄清楚如何成功地做到這一點。以下是我嘗試過的一些事情,只是為了大致了解如何做到這一點:response=requests.get(url + id, headers=h, params=p)messages=json.loads(response.text)for message in messages:    print(message['body'])^^ 在這里我只是想看看我是否可以引用特定消息的正文,沒有工作。r=requests.get(url + id, headers=h, params=p)inbound_dict = {}inbound=json.loads(r.text)for item in inbound['messages']:    inbound_dict[item['conversationId']] = item['body']print(inbound_dict)^^ 這個確實有點作用,但不允許我有效地組織數據以便稍后調用。當我打印字典時,它會顯示最新的值,因為鍵不是唯一的......所以它是覆蓋而不是附加。這就是讓我覺得最好列出清單的原因。最后,我想要一個解決方案,將數據組織conversationId在字典或類似結構中的類似結構中,我可以通過conversationId、 或引用消息msgId,以及一種簡潔易讀的方式來存儲所有數據......:)Messages     |___                  msgId:         |_conversationId-[         |                 body         |                 msgId:         |_conversationId-[         |                 body         |                 msgId:         |_conversationId-[                           body最后,這是一個 json 示例。請記住,我仍在學習和掌握 python 的速度。謝謝大家的時間!
查看完整描述

3 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

您可以使用這樣的組合列表和字典理解來做到這一點:


import json

from pprint import pprint



response = b'{"id":1005672,"messages":[{"id":4461048,"body":"Mnow test test","conversationId":1005672,"locationId":2045,"contactId":12792806,"assignedUserId":0,"status":"RECEIVED","error":null,"kind":"INCOMING","outgoing":false,"reviewRequest":false,"type":"SMS","readDate":0,"respondedDate":0,"sentDate":1576783232355,"attachments":[]},{"id":4461049,"body":"THIS NUMBER DOES NOT CURRENTLY ACCEPT TEXT MESSAGES PLEASE CALL (716) 444-4444 TO WORK WITH ONE OF OUR INTAKE SPECIALISTS","conversationId":1005672,"locationId":2045,"contactId":12792806,"assignedUserId":0,"status":"RECEIVED","error":null,"kind":"AUTO_RESPONSE","outgoing":true,"reviewRequest":false,"type":"SMS","readDate":0,"respondedDate":0,"sentDate":1576783233546,"attachments":[]},{"id":4620511,"body":"test sms,test sms","conversationId":1005672,"locationId":2045,"contactId":12792806,"assignedUserId":17297,"status":"DELIVERED","error":null,"kind":"API","outgoing":true,"reviewRequest":false,"type":"SMS","readDate":0,"respondedDate":0,"sentDate":1577987093930,"attachments":[]}]}'


data = json.loads(response)


messages = [

    {'id': message['id'],

     'conversationId': message['conversationId'],

     'body': message['body']} for message in data['messages']

]


pprint(messages, sort_dicts=False)

輸出:


[{'id': 4461048, 'conversationId': 1005672, 'body': 'Mnow test test'},

 {'id': 4461049,

  'conversationId': 1005672,

  'body': 'THIS NUMBER DOES NOT CURRENTLY ACCEPT TEXT MESSAGES PLEASE CALL '

          '(716) 444-4444 TO WORK WITH ONE OF OUR INTAKE SPECIALISTS'},

 {'id': 4620511, 'conversationId': 1005672, 'body': 'test sms,test sms'}]

您可以使處理更加數據驅動,并消除理解中的大量重復編碼,從而使其更加簡潔,如下所示:


import json

from pprint import pprint


data_points = 'id', 'conversationId', 'body'

response = b'{"id":1005672,"messages":[{"id":4461048,"body":"Mnow test test","conversationId":1005672,"locationId":2045,"contactId":12792806,"assignedUserId":0,"status":"RECEIVED","error":null,"kind":"INCOMING","outgoing":false,"reviewRequest":false,"type":"SMS","readDate":0,"respondedDate":0,"sentDate":1576783232355,"attachments":[]},{"id":4461049,"body":"THIS NUMBER DOES NOT CURRENTLY ACCEPT TEXT MESSAGES PLEASE CALL (716) 444-4444 TO WORK WITH ONE OF OUR INTAKE SPECIALISTS","conversationId":1005672,"locationId":2045,"contactId":12792806,"assignedUserId":0,"status":"RECEIVED","error":null,"kind":"AUTO_RESPONSE","outgoing":true,"reviewRequest":false,"type":"SMS","readDate":0,"respondedDate":0,"sentDate":1576783233546,"attachments":[]},{"id":4620511,"body":"test sms,test sms","conversationId":1005672,"locationId":2045,"contactId":12792806,"assignedUserId":17297,"status":"DELIVERED","error":null,"kind":"API","outgoing":true,"reviewRequest":false,"type":"SMS","readDate":0,"respondedDate":0,"sentDate":1577987093930,"attachments":[]}]}'

data = json.loads(response)

messages = [{dp: message.get(dp) for dp in data_points}

                for message in data['messages']]


pprint(messages, sort_dicts=False)


查看完整回答
反對 回復 2022-07-19
?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

我的理解是,您希望您的消息采用可通過對話檢索的數據結構。這是我要做的:


from pprint import pprint


#with this data structure whenever we refer to a conversation, if it

#doesn't exist, it gets created

from collections import defaultdict

inbound_dict = defaultdict(dict) 


inbound=json.loads(data)

for item in inbound['messages']:

    print (item)


    current_conversation=inbound_dict[item['conversationId']]

    #inbound_dict retrives the apropriate conversation,

    #   or creates a new one for us to fill

    current_conversation[item["id"]] = item['body'] #add our item to it.


    #or if there's a chance we might want *everything* else about the

    #message later even if just the date in order to preserve

    #conversation ordering or whatever:


    #currentconversation[item["id"]] = item


pprint(inbound_dict)

但這可能是矯枉過正,這取決于你以后要做什么處理,以及它是什么處理。如果您只是讓他們選擇一個對話,并顯示最后 20 條消息,那么可切片的列表可能是內部數據結構的最佳選擇,在這種情況下,我會這樣做:


from pprint import pprint


#with this data structure whenever we refer to a conversation, if it

#doesn't exist, it gets created

from collections import defaultdict

inbound_dict = defaultdict(list) 


inbound=json.loads(data)

for item in inbound['messages']:

    print (item)


    current_conversation=inbound_dict[item['conversationId']]

    #inbound_dict retrives the apropriate conversation,

    #   or creates a new one for us to fill


    current_conversation.append(

        (item["id"], item['body'])

        ) # here we add our item to it, in this case a tuple of id and body


    #or if there's a chance we might want *everything* else about the

    #message later even if just the date in order to preserve

    #conversation ordering or whatever:


    #currentconversation.append(item)


pprint(inbound_dict)

基本相同的操作,但 defaultdict 為我們提供了不同類型的內部集合來填充。


查看完整回答
反對 回復 2022-07-19
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

如果您可以擁有多個具有相同會話 ID 的項目,那么您可以執行以下操作:


r=requests.get(url + id, headers=h, params=p).json()

inbound_dict = {}

for item in r['messages']:

    conv_id = item['conversationId']

    if conv_id not in inbound_dict:

        inbound_dict[conv_id]=[{'msg_id' : item['id'], 'body' : item['body']}]

    else:

        inbound_dict[conv_id].append({'msg_id' : item['id'], 'body' : item['body']})


print(inbound_dict)

生成的數據結構是一個以 conversation_id 作為鍵的字典,每個 conversation_id 映射到一個list項目dict。每個項目都存儲特定消息的 message_id 和正文。然后,您可以通過檢索為 conv_id 鍵存儲的消息列表來迭代特定對話的消息。


或者,您可以選擇以下數據結構進行映射: {conv_id -> { message_id : {message info ...}, ...}.


這可以像這樣實現:


r=requests.get(url + id, headers=h, params=p).json()

inbound_dict = {}

for item in r['messages']:

    conv_id = item['conversationId']

    if conv_id not in inbound_dict:

        inbound_dict[conv_id]={item['id'] : {'msg_id' : item['id'], 'body' : item['body']}}

    else:

        inbound_dict[conv_id][item['id']] = {'msg_id' : item['id'], 'body' : item['body']}


print(inbound_dict)


在這種情況下,如果您知道 con_id 和 message_id,則可以直接從對話中訪問消息。


所以它真的取決于這個數據結構的下游實用程序。


請注意,上述內容也可以通過列表推導來完成。


查看完整回答
反對 回復 2022-07-19
  • 3 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號