You need to enable JavaScript to run this app. 使用Logstash Ruby转换JSON日志中HTTP请求头的数组结构
优惠活动
大模型
产品
解决方案
定价
更多

使用Logstash Ruby转换JSON日志中HTTP请求头的数组结构

解决方案

核心逻辑是遍历headers下的数组元素,将每个元素的name和value提取为新的键值对,替换原数组结构即可,其余字段保持不变。

require 'json'

# 替换为你实际读取的原始JSON字符串
raw_json = <<~JSON
{
  "host": "hostname",
  "httpRequest": {
    "httpVersion": "HTTP/1.1",
    "headers": [
      {"name": "X-Forwarded-For", "value": "1.1.1.1"},
      {"name": "X-Forwarded-Prot", "value": "https"},
      {"name": "X-Forwarded-Port", "value": "443"}
    ],
    "httpMethod": "post"
  },
  "action": "allow"
}
JSON

# 解析JSON为Ruby哈希对象
data = JSON.parse(raw_json)

# 转换headers结构:数组转键值对哈希
data['httpRequest']['headers'] = data['httpRequest']['headers'].each_with_object({}) do |item, new_hash|
  new_hash[item['name']] = item['value']
end

# 输出格式化后的结果
puts JSON.pretty_generate(data)

运行后输出的结构完全符合要求:

{
  "host": "hostname",
  "httpRequest": {
    "httpVersion": "HTTP/1.1",
    "headers": {
      "X-Forwarded-For": "1.1.1.1",
      "X-Forwarded-Prot": "https",
      "X-Forwarded-Port": "443"
    },
    "httpMethod": "post"
  },
  "action": "allow"
}

如果是批量处理多条日志,把转换逻辑封装为方法遍历处理每条日志即可,只要原始headers数组内的name没有重复,就不会出现字段覆盖问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 23:00:03