简体   繁体   中英

Iterate JSON & append to a dictionary?

I've searched but can't seem to get a working example specifically for what i'm trying to do here. I'm working with an api that returns a bunch of lines of json. I would like to iterate through all of the key/value pairs and store only the relevant ones to another dictionary to be used/referenced later on.

What I have tried works for the most part, however when I print the contents of the dictionary object it only returns the newest key/value pair... I would like to know how to APPEND to the dictionary, so that when I print it, I get a nice long list of key/value pairs.

Here's the code:

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)

I know it's got to be something simple I'm missing. I've tried inbound_dict.append() but obviously that's not quite right.

You can see in the image below where the red lines are, that just shows where each of the different json "instances" end. For context, this is an sms messaging app and each json response represents a single message.

这是我需要解析的返回 json 的示例输出

And, here are the first 2 "json's" in text form:

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":[]},...

I think you want to do:

r=requests.get(url + id, headers=h, params=p)
inbound_dict = {}
inbound=json.loads(r.text)
for item in inbound['messages']:
    inbound_dict[item['id']] = item['body']
print(inbound_dict)

Given this data:

'{"id": 1005672, "messages": [{"id": 4461048, "body": "Mnow test test", "conversationId": 1005672, "locationId": 2045, "contactId": 12792806, "assignedUserId": 0, "status": "RECEIVED", "error": "", "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": "", "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": "", "kind": "API", "outgoing": true, "reviewRequest": false, "type": "SMS", "readDate": 0, "respondedDate": 0, "sentDate": 1577987093930, "attachments": []}]}'

The output is:

{    
    4461048: 'Mnow test test', 
    4461049: 'THIS NUMBER DOES NOT CURRENTLY ACCEPT TEXT MESSAGES PLEASE CALL (716) 444-4444 TO WORK WITH ONE OF OUR INTAKE SPECIALISTS', 
    4620511: 'test sms,test sms'
}

Something like this might work:

# initialize variables:
inbound_dictionary_list = []

for item in inbound['messages']:

    # extract key, value:
    key = item['conversationId']
    value = item['body']

    # pack into dictionary object:
    parsed_item = {key:value}

    # update existing dictionary:
    inbound_dictionary_list.append(parsed_item)

Details: https://www.w3schools.com/python/ref_dictionary_update.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM