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

如何从带日志前缀的字符串中提取内部JSON对象?

提取日志字符串中的JSON结构方法

下面是几种提取日志里内部JSON结构的实用方法:

方法一:Python代码处理

用Python直接定位JSON的起始和结束位置,快速提取:

log_str = '''[ERROR] 2020-10-01T04:46:37.sdfsdqs889dgsdg9dgdf {
"correlation_id": "asdfsdf-dsfasdfa-adfadsf-asdf",
"invocation_timestamp": null,
"invoked_component": "lambda",
"invoker_agent": null,
"message": {
"errorMessage": "Unauthorized",
"statusCode": 401
},
"message_type": "ERROR",
"original_source_app": "",
"response_timestamp": "2020-10-01 04:46:37.121436",
"status": 401,
"target_idp_application": "",
"timezone": "UTC"
}'''

# 定位JSON起始的第一个{
start_pos = log_str.find('{')
# 定位JSON结束的最后一个},+1是为了包含这个}
end_pos = log_str.rfind('}') + 1
# 提取并输出JSON部分
json_content = log_str[start_pos:end_pos]
print(json_content)

运行这段代码就能得到你要的纯JSON结构。

方法二:命令行工具处理(Linux/macOS环境)

如果习惯用命令行,这两个工具能快速搞定:

用sed命令

echo '[ERROR] 2020-10-01T04:46:37.sdfsdqs889dgsdg9dgdf {
"correlation_id": "asdfsdf-dsfasdfa-adfadsf-asdf",
"invocation_timestamp": null,
"invoked_component": "lambda",
"invoker_agent": null,
"message": {
"errorMessage": "Unauthorized",
"statusCode": 401
},
"message_type": "ERROR",
"original_source_app": "",
"response_timestamp": "2020-10-01 04:46:37.121436",
"status": 401,
"target_idp_application": "",
"timezone": "UTC"
}' | sed '1s/.*{/{/'

原理是把第一行里{之前的所有内容替换掉,只保留{及后面的JSON部分。

用jq命令(更稳妥,支持复杂JSON)

jq能自动校验并格式化JSON,先通过awk去掉前缀,再用jq处理:

echo '[ERROR] 2020-10-01T04:46:37.sdfsdqs889dgsdg9dgdf {
"correlation_id": "asdfsdf-dsfasdfa-adfadsf-asdf",
"invocation_timestamp": null,
"invoked_component": "lambda",
"invoker_agent": null,
"message": {
"errorMessage": "Unauthorized",
"statusCode": 401
},
"message_type": "ERROR",
"original_source_app": "",
"response_timestamp": "2020-10-01 04:46:37.121436",
"status": 401,
"target_idp_application": "",
"timezone": "UTC"
}' | awk '{sub(/^.*{/,"{"); print}' | jq .

方法三:手动处理(适合少量数据)

如果只是偶尔处理几条日志,直接选中从第一个{到最后一个}的所有内容,复制粘贴就行,简单高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:40:34