我是Go的新手,在弄清楚如何打印出我創(chuàng)建的JSON時遇到了麻煩。我正在使用“ encoding / json”,并且正在返回一個[] byte。但是,當我打印出來時,我得到:cannot use json_msg (type []byte) as type string in function argument收到此消息后,我嘗試將[] byte數(shù)組轉(zhuǎn)換為字符串或空接口。但是我似乎無法使其正常工作。有任何想法嗎?相關代碼如下:type Message struct { Id int Name string}for _, row := range rows { m := Message{row.Int(0), row.Str(1)} json_msg, err := json.Marshal(m) if err == nil { panic(err) }//if //tried below to print out a interface, didn't work either //var f interface{} //err = json.Unmarshal(json_msg, &f) fmt.Fprintf(c.ResponseWriter, json_msg)}//for
3 回答

海綿寶寶撒
TA貢獻1809條經(jīng)驗 獲得超8個贊
您json_msg
在Printf
類型函數(shù)中string
用作格式字符串,僅將其用作格式字符串([]byte
和string
是不同的類型。盡管可以將它們彼此轉(zhuǎn)換)。寫入字節(jié)片的正確方法是指定格式字符串:
fmt.Fprintf(WRITER_OBJ, "%s", json_msg)
這將打印[]byte
Unicode內(nèi)容。在Fprintf / Printf中,不應將變量用作格式字符串。我認為這不會像C語言那樣有問題。但是,如果您的JSON中包含“%”,則可能會引起問題。
- 3 回答
- 0 關注
- 529 瀏覽
添加回答
舉報
0/150
提交
取消