从 Json 中提取

Extracting from Json

通过其中一种方法,我的输出低于输出

        {'Records': [{'messageId': '2953dfd5-d848-42b2-a60b-43df00ec8e5f', 
       'receiptHandle': 'AQEBPMr5RbW3T2DG4pAYi+', 'body': 
      'I am still trying', 'attributes': {'ApproximateReceiveCount': '1', 
        'SentTimestamp': '1552073955807', 'SenderId': '944198216610', 
        'ApproximateFirstReceiveTimestamp': '1552073955816'}, 
        'messageAttributes': {}, 'md5OfBody': 
         '2111a742ddbdac2d862fa6a204f7dc85', 'eventSource': 'aws:sqs', 
          'eventSourceARN': 'arn:aws:sqs:us-east- 
         1:944198216610:LambadaQueue', 'awsRegion': 'us-east-1'}]}

现在我想从中获取 body 的值,所以我在下面使用了

正文=事件['Records'][0][0]['body']

但这不是working.Can请你帮我弄清楚我做错了什么?

如果您尝试获取 "body" 元素的值,看起来您应该跳过查找中的第二个 [0]。正确格式化后,它看起来像这样:

{
  "Records": [
    {
      "messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
      "receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
      "body": "I am still trying",
      "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "1552073955807",
        "SenderId": "944198216610",
        "ApproximateFirstReceiveTimestamp": "1552073955816"
      },
      "messageAttributes": { },
      "md5OfBody": "2111a742ddbdac2d862fa6a204f7dc85",
      "eventSource": "aws:sqs",
      "eventSourceARN": "arn:aws:sqs:us-east-1:944198216610: LambadaQueue",
      "awsRegion": "us-east-1"
    }
  ]
}

因此,要获取 "Records" 中第一条记录的字段 "body" 的值,您应该这样做: body=event['Records'][0]['body']

What am I doing wrong?

Records 键是一个列表,您可以使用该项目的索引号从列表中 select 项目。

json_string = {
              "Records": [
    {
      "messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
      "receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
      "body": "I am still trying",
      "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "1552073955807",
        "SenderId": "944198216610",
        "ApproximateFirstReceiveTimestamp": "1552073955816"
      },
      "messageAttributes": { },
      "md5OfBody": "2111a742ddbdac2d862fa6a204f7dc85",
      "eventSource": "aws:sqs",
      "eventSourceARN": "arn:aws:sqs:us-east-1:944198216610: LambadaQueue",
      "awsRegion": "us-east-1"
    }
  ]
}

因此,当您执行 json_string['Records'][0] 时,此 select 是列表中的第一项,它又是一个字典:

{
  "messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
  "receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
  "body": "I am still trying",
 ....}

现在,如果您这样做 json_string['Records'][0][0],您正试图像访问列表中的项目一样访问字典键(使用索引号 0),这在语法上是不正确的。如果您想访问 'messageId' 的值,您可以按名称访问密钥,例如 json_string['Records'][0]['messageId'],或者如您的问题,"body" 密钥的值如下所示:

`json_string['Records'][0]['body']`

 #Output:
 I am still trying