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

如何在Python中解析非标准JSON格式的AWS HTTP日志为字典

解决AWS非标准日志转Python字典的问题

你的日志是JS对象风格格式,两个关键问题导致解析失败:无引号的键,以及[Object: null prototype] { }这种Node.js特有的空对象表示。可以通过正则修复格式后用json5解析,步骤如下:

步骤1:修复日志格式

用正则给所有无引号的键添加双引号,同时替换特殊的空对象表示:

import re
import json5

# 原始日志文本
log_content = """{
  resource: '',
  path: '',
  httpMethod: 'POST',
  headers: {
    accept: '*/*',
  },
  multiValueHeaders: {
    accept: [ '*/*' ],
    'accept-encoding': [ 'gzip, deflate, br' ],
    'accept-language': [ 'zh-CN,zh-Hans;q=0.9' ]
  },
  queryStringParameters: {},
  multiValueQueryStringParameters: null,
  pathParameters: null,
  stageVariables: null,
  requestContext: {
    resourceId: '',
    resourcePath: '',
    identity: {
      cognitoIdentityPoolId: null,
      accountId: null,
      cognitoIdentityId: null,
      caller: null,
      sourceIp: '',
      principalOrgId: null,
      accessKey: null,
      cognitoAuthenticationType: null
    },
    domainName: '',
    apiId: ''
  },
  body: [Object: null prototype] { },
  isBase64Encoded: false
}"""

# 1. 给无引号的键添加双引号(匹配行首缩进后的合法标识符)
fixed_content = re.sub(r'^\s*([a-zA-Z_][\w]*):', r'"\1":', log_content, flags=re.MULTILINE)
# 2. 将Node.js风格的空对象替换为标准JSON空字典
fixed_content = fixed_content.replace('[Object: null prototype] { }', '{}')

步骤2:用json5解析

修复后的格式符合json5的语法规范,可以直接解析为Python字典:

parsed_dict = json5.loads(fixed_content)
print(parsed_dict)
print(type(parsed_dict))  # 输出: <class 'dict'>

说明

  • 最初用json5失败是因为[Object: null prototype] { }不是json5支持的语法,必须先替换。
  • 正则匹配规则只处理行首缩进后的合法标识符(字母/下划线开头,字母/数字/下划线组成),不会影响已经带引号的键(比如'accept-encoding')。
  • json5支持单引号字符串、尾逗号等JS风格语法,完美适配这类日志格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:10:49