3 回答

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)

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 為我們提供了不同類型的內部集合來填充。

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,則可以直接從對話中訪問消息。
所以它真的取決于這個數據結構的下游實用程序。
請注意,上述內容也可以通過列表推導來完成。
添加回答
舉報