Go Template移除特定字段:删除数据中的time列与时间戳值
使用Go Template处理JSON:移除指定字段并修正键名
需求说明
给定如下原始JSON数据:
{ "time":"2022-08-24T06:00:00Z", "duration":0, "level":"OK", "data":{ "series":[{ "name":"gnb_kpi", "tags":{ "ID":"1017", "_field":"Success_rate%", "cluster_id":"ec17-1017", "swversion":"6.0" }, "columns":["time","_value"], "values":[["2022-08-24T06:00:00Z","100"]] }] }, "previousLevel":"CRITICAL", "recoverable":true }
需要通过Go Template实现两个目标:
- 移除
columns数组中的time字段,同时移除values数组内的时间戳元素 - 将
tags中的swversion键名修正为swVersion
期望输出:
{ "time":"2022-08-24T06:00:00Z", "duration":0, "level":"OK", "data":{ "series":[{ "name":"gnb_kpi", "tags":{ "ID":"1017", "_field":"Success_rate%", "cluster_id":"ec17-1017", "swVersion":"6.0" }, "columns":["_value"], "values":[["100"]] }] }, "previousLevel":"CRITICAL", "recoverable":true }
实现方案
1. 定义对应JSON的结构体
先将原始JSON解析到Go结构体中,方便模板绑定数据:
package main import ( "encoding/json" "fmt" "os" "text/template" ) type KPIResponse struct { Time string `json:"time"` Duration int `json:"duration"` Level string `json:"level"` Data Data `json:"data"` PreviousLevel string `json:"previousLevel"` Recoverable bool `json:"recoverable"` } type Data struct { Series []Series `json:"series"` } type Series struct { Name string `json:"name"` Tags map[string]string `json:"tags"` Columns []string `json:"columns"` Values [][]string `json:"values"` }
2. 编写Go Template
模板中通过遍历和条件判断处理字段过滤与键名修正,同时处理JSON格式的逗号分隔问题:
func main() { // 原始JSON数据 rawJSON := []byte(`{ "time":"2022-08-24T06:00:00Z", "duration":0, "level":"OK", "data":{ "series":[{ "name":"gnb_kpi", "tags":{ "ID":"1017", "_field":"Success_rate%", "cluster_id":"ec17-1017", "swversion":"6.0" }, "columns":["time","_value"], "values":[["2022-08-24T06:00:00Z","100"]] }] }, "previousLevel":"CRITICAL", "recoverable":true }`) // 解析JSON到结构体 var kpi KPIResponse err := json.Unmarshal(rawJSON, &kpi) if err != nil { fmt.Println("解析JSON失败:", err) return } // 注册模板需要的辅助函数 funcMap := template.FuncMap{ "add": func(a, b int) int { return a + b }, } // 定义并解析模板 tmpl, err := template.New("kpiProcessor").Funcs(funcMap).Parse(`{{- $json := . -}} { "time": "{{ $json.time }}", "duration": {{ $json.duration }}, "level": "{{ $json.level }}", "data": { "series": [ {{- range $index, $series := $json.data.series }} {{- if $index }},{{ end }} { "name": "{{ $series.name }}", "tags": { {{- $tagCount := len $series.tags }} {{- $current := 0 }} {{- range $key, $value := $series.tags }} {{- if eq $key "swversion" }} "swVersion": "{{ $value }}" {{- else }} "{{ $key }}": "{{ $value }}" {{- end }} {{- $current = add $current 1 }} {{- if lt $current $tagCount }},{{ end }} {{- end }} }, "columns": [ {{- $firstCol := true }} {{- range $col := $series.columns }} {{- if ne $col "time" }} {{- if not $firstCol }},{{ end }}"{{ $col }}" {{- $firstCol = false }} {{- end }} {{- end }} ], "values": [ {{- range $valIndex, $valArr := $series.values }} {{- if $valIndex }},{{ end }}[ {{- $firstVal := true }} {{- range $vIndex, $val := $valArr }} {{- if ne $vIndex 0 }} {{- if not $firstVal }},{{ end }}"{{ $val }}" {{- $firstVal = false }} {{- end }} {{- end }} ] {{- end }} ] } {{- end }} ] }, "previousLevel": "{{ $json.previousLevel }}", "recoverable": {{ $json.recoverable }} }`) if err != nil { fmt.Println("解析模板失败:", err) return } // 执行模板并输出结果 err = tmpl.Execute(os.Stdout, kpi) if err != nil { fmt.Println("执行模板失败:", err) return } }
关键处理逻辑
- 字段过滤:遍历
columns时跳过time字段,遍历values数组时跳过索引为0的时间戳元素 - 键名修正:遍历
tags时判断键名,将swversion替换为swVersion - 格式处理:用
$firstCol、$firstVal和add函数处理JSON数组/对象的逗号分隔,避免格式错误
内容的提问来源于stack exchange,提问作者Pratik das baghel
相关产品推荐
相关产品推荐

