
本文讲解如何使用 go 的 `encoding/json` 包安全、准确地解析 url 查询参数(如 `filters`)中传递的合法 json 字符串,并提取结构化字段值,同时指出原始 url 中 json 格式错误的问题及修复方法。
在 Go Web 开发中,常需从 HTTP 请求的查询参数中读取结构化数据(如过滤条件)。但需注意:URL 查询参数本身是键值对字符串,不能直接包含未编码的 JSON 对象或数组——尤其当 JSON 中含有引号、冒号、逗号等特殊字符时,会破坏 URL 解析逻辑。
例如,原始 URL:
http://127.0.0.1:3001/find?field=hostname&field=App&filters=["hostname":"example.com,"type":"vm"]
该 filters 值 不是合法 JSON:方括号 [] 表示数组,但内部却写成了对象语法(缺少 {}),且键名未用双引号包裹("hostname" 缺失引号),逗号后也缺少空格与引号闭合,导致 json.Unmarshal 必然失败。
✅ 正确做法是:
- 服务端要求客户端发送符合 JSON 规范的字符串(推荐使用对象 {...} 而非数组);
- 对 JSON 字符串进行 URL 编码(避免特殊字符干扰 query 解析);
- 使用 url.Query().Get("filters") 获取解码后的字符串;
- 用 json.Unmarshal 解析为 Go 原生类型(如 map[string]string 或自定义 struct)。
✅ 正确示例(服务端解析逻辑)
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func handler(w http.ResponseWriter, r *http.Request) {
// 1. 获取 filters 参数值(自动完成 URL 解码)
filtersStr := r.URL.Query().Get("filters")
if filtersStr == "" {
http.Error(w, "missing 'filters' parameter", http.StatusBadRequest)
return
}
// 2. 定义目标结构(更推荐:使用 struct 提升类型安全)
var filters map[string]string
// 或:var filters struct { Hostname string `json:"hostname"`; Type string `json:"type"` }
// 3. 解析 JSON
if err := json.Unmarshal([]byte(filtersStr), &filters); err != nil {
http.Error(w, "invalid JSON in 'filters': "+err.Error(), http.StatusBadRequest)
return
}
// 4. 安全提取字段(避免 panic)
hostname, ok1 := filters["hostname"]
typ, ok2 := filters["type"]
if !ok1 || !ok2 {
http.Error(w, "required fields 'hostname' and 'type' not found", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Hostname: %s, Type: %s", hostname, typ)
}
func main() {
http.HandleFunc("/find", handler)
log.Println("Server starting on :3001...")
log.Fatal(http.ListenAndServe(":3001", nil))
}? 关键注意事项
- 永远不要信任客户端输入:必须校验 filters 是否为空、JSON 是否合法、必需字段是否存在;
- 推荐使用结构体而非 map[string]string,可结合 JSON tag 实现字段映射与默认值控制;
-
客户端应 URL 编码 JSON 字符串,例如:
# 原始 JSON: {"hostname":"example.com","type":"vm"} # 编码后(curl 示例): curl "http://127.0.0.1:3001/find?filters=%7B%22hostname%22%3A%22example.com%22%2C%22type%22%3A%22vm%22%7D"Go 的 url.Parse() 和 r.URL.Query() 会自动解码,无需手动调用 url.QueryUnescape;
- 若需支持数组型过滤器(如 filters=[{"key":"host","value":"a.com"},{"key":"env","value":"prod"}]),应定义对应 slice 结构体并解析。
✅ 总结
解析 URL 中的 JSON,核心在于「规范输入 + 健壮解析」:确保前端传入的是合法、编码过的 JSON 字符串,后端则通过 encoding/json 安全反序列化,并辅以字段存在性检查与错误处理。跳过格式校验或尝试手动字符串切割,将导致难以调试的运行时错误与安全风险。










