慕容708150
解决问题的不同方法。简单(安全)的方法:// import "fmt" "strings"j := fmt.Sprintf(`{"data":{"1":%s}}`, strings.Join(strings.Fields(fmt.Sprintf("%d", results)), ","))之前在评论中,我提出了这种更懒惰的方法,没有字符串,但它不太安全:// import "fmt"j := fmt.Sprintf("%#v",*results); j = "{ \"data\": { \"1\": \""+j[7:len(j)-1]+"\"} }"// works when the array size is between 1 and 9, above this, the "7" must increase现在使用原生 golang json 基础结构。这里是一个示例,使用硬编码results := []uint{0, 0, 0, 0, 0, 0}package mainimport ( "encoding/json" "io/ioutil" "log")type d struct { Data o `json:"data"`}type o struct { One []uint `json:"1"`}func main() { results := []uint{0, 0, 0, 0, 0, 0} j, _ := json.Marshal(&d{Data:o{One:results}}) err := ioutil.WriteFile("output.json", []byte(j), 0777) // i can't test here I don't know if []byte(j) or []byte(string(j)) should be used if err != nil { log.Fatal(err) }}但是,一旦你的数组是uint8而不是uint,golang的json编码[]uint8(与[]byte相同)作为base64字符串,我们必须实现我们自己的Marshaller,通过实现MarshalJSON来避免这种行为,就像如何在Go中将byte/uint8数组封送为json数组一样。package mainimport ( "encoding/json" "io/ioutil" "strings" "log" "fmt")type d struct { Data o `json:"data"`}type o struct { One []uint8 `json:"1"`}func (t *o) MarshalJSON() ([]byte, error) { var one string if t.One == nil { one = "null" } else { one = strings.Join(strings.Fields(fmt.Sprintf("%d", t.One)), ",") } jsonresult := fmt.Sprintf(`{"1":%s}`, one) return []byte(jsonresult), nil}func main() { results := []uint8{0, 0, 0, 0, 0, 0} j, _ := json.Marshal(&d{Data:o{One:results}}) err := ioutil.WriteFile("output.json", []byte(j), 0777) // i can't test here I don't know if []byte(j) or []byte(string(j)) should be used if err != nil { log.Fatal(err) }}