解析 json 中的字符串 Python

Parse json string in Python

一个简单的,但我还没有完全理解 Python...

中的嵌套列表和 json 结构的解析

这是我要解析的原始消息。

{
    "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"
        }
    ]
}

我正在尝试提取正文部分中的消息,最后得到一个字符串 "ChiliChallenge.mp4\"

谢谢! 本质上,我只是不断收到 TypeError: string indices must be integers 或解析正文但没有在没有错误的情况下进一步进入列表。

这是我的尝试:

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)

假设您的消息是短语, 我像这样重建你的代码: phrase_2 = phrase["Records"] print(phrase_2[0]["body"])

然后就可以正常工作了。因为记录的开头,它看起来像一个数组,所以你需要组织它。

你可以使用json.loads加载字符串

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'