Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

golang 生成 json 只能通过 struct 来么?

网上给的方案都是先根据你的 json 结构定义一个 struct,然后 json.Marshal,我在用的时候觉得好麻烦。

如果有很多 json 结构,那岂不是都要先定义结构体。我去 github 上找了一下,没有可以直接通过 api 生成 json 的库。比如 c 语言的 cJSON_add* 就很方便啦。

刚入 golang,有了解的朋友请指教一下,先行谢过。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以用 map[string]interface{}

b, _ := json.Marshal(map[string]interface{}{
    "a": "aa",
    "b": "bb",
    "c": "cc",
    "d": "dd",
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...