为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕斯王 2022-08-01 17:02:13
我有一个不断打印的数组/结构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。
查看完整描述

2 回答

?
慕容708150

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)

    }

}


查看完整回答
反对 回复 2022-08-01
?
素胚勾勒不出你

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)


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 106 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号