使用AWS Lambda从AWS SNS读取时修改JSON消息

问题描述 投票:0回答:1

我有一个上游应用程序向SNS主题发送以下JSON消息。我们使用AWS lambda函数在S3中保存此JSON对象:

{
"processResult": {
    "processName": "XYZ",
    "stageResults": {
        "Read Files": {
            "status": "PROCESSED",
            "error": "",
            "timeTaken": 26064469473
        },
        "Convert Files": {
            "status": "PROCESSED",
            "error": "",
            "timeTaken": 97968896
        }
    },
    "processMetrics": {
        "filesProcessed": 1157,
        "filesWithExceptionCount": 1,
        "timeTaken": "367.460031s",
        "metricsCalcTime": "6.061847s",
        "totalTimeTaken": "373.521878s"
    },
    "succeeded": true
  }
}

如果你在“stageResults”STRUCT中观察,我有空格的属性,比如“Read Files”和“Convert Files”,当我尝试使用AWS Athena(AWS Glue Crawler)从S3读取这个JSON时,我得到了以下错误:

    HIVE_METASTORE_ERROR: com.facebook.presto.spi.PrestoException: Error: : expected at the position 51 of 'struct<....
......but ' ' is found. (Service: null; Status Code: 0; Error Code: null; Request ID: null)

但是当我通过修改“stageResults”STRUCT(如“Read_Files”和“Convert_Files”)手动编辑JSON消息时,我能够成功地使用AWS Athena表读取和查询JSON。

以下是来自AWS Lambda的一段代码,它在SNS主题上触发,读取JSON消息并将其保存在S3中:

import json
import boto3
import random
import string

file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(16)])

def lambda_handler(event, context):
    target_bucket = 'bucket-name'
    target_key = 'input=clientdata/'  + file_name + '.json'
    s3 = boto3.resource('s3')
    for record in event['Records']:
        payload = record["body"]
        data = json.loads(payload)
        print(data)
        print("copying JSON message...")
        s3.Object('target_bucket', 'target_key').put(
            Body=(bytes(json.dumps(data).encode('UTF-8')))
        )

现在,我想知道在使用AWS Lambda将其保存到S3之前如何修改此JSON消息。任何帮助表示赞赏。

python aws-lambda amazon-sns amazon-athena aws-glue
1个回答
0
投票

如果您只想将包含空格的每个键更改为适合您需要的内容,则可能会:

import re
wrong_keys = []
for key in data.keys():
    if key.strip().find(" ") != -1:
        wrong_keys.append(key)
for key in wrong_key:
  data[re.sub(r'[\W]+', '_',key)] = data.pop(key)
© www.soinside.com 2019 - 2024. All rights reserved.