本文介绍如何利用 go-simplejson 库解析嵌套 json,并遍历 `data.docs` 数组中的每个对象,将其分别序列化为独立的格式化 json 文件。同时对比标准库方案,强调适用场景与性能权衡。
在 Go 中处理动态结构的 JSON(如字段名未知、嵌套层级灵活)时,bitly/go-simplejson 是一个轻量且实用的选择。但其 API 并未直接暴露对底层 map[string]interface{} 的迭代方法,需结合类型断言手动展开。
以下是以你提供的 JSON 结构为例的完整实现流程:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
simplejson "github.com/bitly/go-simplejson"
)
func main() {
j, err := ioutil.ReadFile("input.json")
if err != nil {
panic(err)
}
dec, err := simplejson.NewFromReader(bytes.NewReader(j))
if err != nil {
panic(err)
}
docs := dec.Get("data").Get("docs")
if !docs.Exists() {
panic("missing 'data.docs'")
}
docsArray := docs.MustArray()
for i, doc := range docsArray {
// 类型断言:simplejson.Get(...).MustArray() 返回 []interface{},
// 每个元素是 map[string]interface{}(对应 JSON 对象)
m, ok := doc.(map[string]interface{})
if !ok {
panic(fmt.Sprintf("doc[%d] is not a JSON object", i))
}
out := simplejson.New()
for k, v := range m {
out.Set(k, v) // 逐键值对写入新 simplejson 对象
}
b, err := out.EncodePretty()
if err != nil {
panic(err)
}
outpath := fmt.Sprintf("file%d.json", i)
if err := ioutil.WriteFile(outpath, b, 0644); err != nil {
panic(err)
}
fmt.Printf("Wrote %s\n", outpath)
}
}✅ 关键点说明:
⚠️ 注意事项:
作为对比,标准库版本如下(无需额外依赖):
type DataLayout struct {
Data struct {
Docs []map[string]string `json:"docs"`
} `json:"data"`
}
// ... 解析后循环:
for i, doc := range in.Data.Docs {
b, _ := json.MarshalIndent(doc, "", "\t")
ioutil.WriteFile(fmt.Sprintf("f
ile%d.json", i), b, 0644)
}? 总结:go-simplejson 适用于快速原型、schema 不确定或需运行时动态操作 JSON 的场景;而结构明确时,标准库始终是更高效、更稳健的选择。两者并非互斥,而是应依实际需求合理选用。