简体   繁体   中英

Parse json string in Python

A simple one, but I've just not yet been able to wrap my head around parsing nested lists and json structures in Python...

Here is the raw message I am trying to parse.

{
    "Records": [
        {
            "messageId": "1b9c0952-3fe3-4ab4-a8ae-26bd5d3445f8",
            "receiptHandle": "AQEBy40IsvNDy33dOhn4KB8+7apBecWpSuw5OgL9sw/Nf+tM2esLgqmWjGsd4n0oqB",
            "body": "{\n  \"Type\" : \"Notification\",\n  \"MessageId\" : \"dce5c301-029f-55e1-8cee-959b1ad4e500\",\n  \"TopicArn\" : \"arn:aws:sns:ap-southeast-2:062497424678:vid\",\n  \"Message\" : \"ChiliChallenge.mp4\",\n  \"Timestamp\" : \"2020-01-16T07:51:39.807Z\",\n  \"SignatureVersion\" : \"1\",\n  \"Signature\" : \"oloRF7SzS8ipWQFZieXDQ==\",\n  \"SigningCertURL\" : \"https://sns.ap-southeast-2.amazonaws.com/SimpleNotificationService-a.pem\",\n  \"UnsubscribeURL\" : \"https://sns.ap-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:062478:vid\"\n}",
            "attributes": {
                "ApproximateReceiveCount": "1",
                "SentTimestamp": "1579161099897",
                "SenderId": "AIDAIY4XD42",
                "ApproximateFirstReceiveTimestamp": "1579161099945"
            },
            "messageAttributes": {},
            "md5OfBody": "1f246d643af4ea232d6d4c91f",
            "eventSource": "aws:sqs",
            "eventSourceARN": "arn:aws:sqs:ap-southeast-2:062497424678:vid",
            "awsRegion": "ap-southeast-2"
        }
    ]
}

I am trying to extract the Message in the body section, ending up with a string as "ChiliChallenge.mp4\\"

Thanks! Essentially I just keep getting either TypeError: string indices must be integers or parsing the body but not getting any further into the list without an error.

Here's my attempt:

import json

with open ("event_testing.txt", "r") as myfile:
    event=myfile.read().replace('\n', '')
    str(event)
    event = json.loads(event)
    key = event['Records'][0]['body']
    print(key)

you can use json.loads to load string

with open ("event_testing.txt", "r") as fp:
    event = json.loads(fp.read())
    key = json.loads(event['Records'][0]['body'])['Message']
    print(key)


'ChiliChallenge.mp4'

Say your message is phrase, I rebuild your code like: phrase_2 = phrase["Records"] print(phrase_2[0]["body"])

Then it works clearly. Because beginning of the Records, it looks like an array so you need to organized it.

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