猿问

结构/数组格式附加到 JSON 文件

我有一个不断打印的数组/结构


for{

        results, errz := client.ReadHoldingRegisters(0, 3)

        if errz != nil {

            fmt.Printf("%v\n", errz)

        }


        fmt.Printf("results %v\n", results)

    }


打印输出将如下所示。


[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

如何将其添加到json格式中?我对GOLANG很陌生。我把打字打印出来


fmt.Printf("var1 = %T\n", results) 

结果是 []uint8 我需要在 json 格式上另存为 int。


慕斯王
浏览 107回答 2
2回答

慕容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)    }}

素胚勾勒不出你

我曾经遇到过同样的问题,所以我用下面的代码修复了它:// sample-entity.gotype Sample struct {    sample int `db:"sample" json:"sample"`,}写入 json 文件// it will create a new file if exists already toojsonFile, jsonFileError := os.Create(directory + "/[file_name].json")jsonToWrite := []Sample{    {         sample: 1    }      }if jsonFileError != nil {    panic(jsonFileError)}defer jsonFile.Close()// write in json filejsonWriter := json.NewEncoder(jsonFile)jsonWriter.Encode(jsonFile)
随时随地看视频慕课网APP

相关分类

Go
我要回答