2 回答

TA贡献1831条经验 获得超4个赞
解决问题的不同方法。
简单(安全)的方法:
// 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 main
import (
"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 main
import (
"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)
}
}

TA贡献1827条经验 获得超9个赞
我曾经遇到过同样的问题,所以我用下面的代码修复了它:
// sample-entity.go
type Sample struct {
sample int `db:"sample" json:"sample"`,
}
写入 json 文件
// it will create a new file if exists already too
jsonFile, jsonFileError := os.Create(directory + "/[file_name].json")
jsonToWrite := []Sample{
{
sample: 1
}
}
if jsonFileError != nil {
panic(jsonFileError)
}
defer jsonFile.Close()
// write in json file
jsonWriter := json.NewEncoder(jsonFile)
jsonWriter.Encode(jsonFile)
- 2 回答
- 0 关注
- 106 浏览
添加回答
举报