You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决AWS Lambda接收POST请求JSON时自动添加反斜杠的问题

解决Lambda返回JSON带多余反斜杠的问题

问题根源

你遇到的反斜杠问题,本质是JSON双重序列化导致的:前端传入的请求体已经是JSON字符串,如果你再用json.dumps()对这个字符串做序列化,就会把原本的双引号转义成\",最终返回的就是带反斜杠的JSON。

修复步骤

1. 直接返回原始请求体(调试场景)

如果只是调试需要返回请求体,直接把event['body']作为响应的body字段返回,同时设置Content-Type为application/json,不要二次序列化:

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': event['body']
    }

2. 处理请求体后返回(业务场景)

如果需要先解析请求体做变位词检测,先把event['body']转成Python对象,处理完成后再序列化一次:

import json

def lambda_handler(event, context):
    # 解析请求体为Python对象(字典/列表)
    request_data = json.loads(event['body'])
    
    # 这里添加你的变位词检测逻辑
    # 示例:找出变位词对(仅做演示,可替换为你的实际逻辑)
    words = request_data.get('words', [])
    anagram_groups = {}
    for word in words:
        sorted_word = ''.join(sorted(word.lower()))
        if sorted_word not in anagram_groups:
            anagram_groups[sorted_word] = []
        anagram_groups[sorted_word].append(word)
    result = [group for group in anagram_groups.values() if len(group) > 1]
    
    # 序列化处理后的对象为JSON字符串返回
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps(result)
    }

3. 确认SAM模板配置

检查你的template.yaml,确保API路由的内容类型配置正确,避免API Gateway额外转义:

Resources:
  AnagramFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: anagram/
      Handler: app.lambda_handler
      Runtime: python3.11
      Events:
        AnagramApi:
          Type: Api
          Properties:
            Path: /anagram
            Method: post
            ContentType: application/json

为什么正则替换没用?

反斜杠是序列化逻辑错误导致的产物,每次请求都会重新生成,强行用正则替换会破坏JSON结构,而且无法从根源解决问题,所以完全没必要这么做。

内容的提问来源于stack exchange,提问作者ChristianOConnor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:12:40