简体   繁体   English

如何使用 Python 解析 SQS JSON 消息

[英]How to Parse SQS JSON Message with Python

I have been trying to wrap my head around this, but I can't seem to get it to work.我一直试图解决这个问题,但我似乎无法让它发挥作用。 I can drill down into 'Messages' by specifying it in the sqs polling, but can't get deeper in:我可以通过在 sqs 轮询中指定它来深入了解“消息”,但无法深入:

I am retrieving an AWS SQS message:我正在检索一条 AWS SQS 消息:

import boto3

sqs = boto3.client('sqs',
                   aws_access_key_id='<aws-id>',
                   aws_secret_access_key='<aws-key>',
                   region_name='<aws-region>'
                   )

queue_url = '<aws-queue-url'
# Long poll for message on provided SQS queue
response = sqs.receive_message(
    QueueUrl=queue_url,
    MaxNumberOfMessages=1,
    MessageAttributeNames=[
        'Messages'
    ],
    WaitTimeSeconds=20
)

Which returns a JSON response:它返回 JSON 响应:

{
  'Messages': [
    {
      'MessageId': '37b13967-a92e-4b8b-8aef-32341a8e1e32',
      'ReceiptHandle': 'xyz',
      'MD5OfBody': '081f4bdad6fd3d53c88f165a884a39da',
      'Body': '{"inputIDList":["1234","5678"],"eventID":"9337","scheduleEvent":false,"addToList":true,"listID":"7654","clientID":"123-ABC-456"}'
    }
  ],
  'ResponseMetadata': {
    'RequestId': '79dafe96-04d9-5122-8b2a-a89b79a76a46',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'x-amzn-requestid': '79dafe96-04d9-5122-8b2a-a89b79a76a46',
      'date': 'Tue, 01 Oct 2019 16:13:50 GMT',
      'content-type': 'text/xml',
      'content-length': '4792'
    },
    'RetryAttempts': 0
  }
}

All I need to do here is extract the value for 'Body', but I can't quite drill down far enough without erroring out.我在这里需要做的就是提取“Body”的值,但如果不出错,我无法深入挖掘。

What I would like to return is essentially just this as JSON or a string:我想返回的基本上就是 JSON 或字符串:

'{"inputIDList":["1234","5678"],"eventID":"9337","scheduleEvent":false,"addToList":true,"listID":"7654","clientID":"123-ABC-456"}'

I'm extremely new at this.我对此非常陌生。 Any help would be greatly appreciated!任何帮助将不胜感激!

You can get the required output using您可以使用获得所需的 output

print (response['Messages'][0]['Body'])

In adddition to @matesio answer, if you want to store the body of the message as a python dictionary just wrap it with json.loads:除了@matesio 答案之外,如果您想将消息正文存储为 python 字典,只需使用 json.loads 将其包装:

import json
message = json.loads(response['Messages'][0]['Body'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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