登录
首页 >  Golang >  Go问答

修改 JSON 对象的二进制表示

来源:stackoverflow

时间:2024-03-12 08:24:31 318浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《修改 JSON 对象的二进制表示》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我将 a 对象写入文件 f

a := a{42}
bytes, _ := json.marshalindent(a, "", "\t")
f.write(bytes)

a 看起来像:

type a struct {
    a int `json:"a"`
}

然后我更改该对象的字段并将其写入文件:

a.a = 666
f.write(bytes)

结果我只看到了

{
    "a": 42
}{
    "a": 42
}

正如我所料:

{
    "a": 42
}{
    "a": 666
}

我知道我可以通过再次使用 json.marshalindent 来克服它。但我需要对文件进行大量(~10^6)次写入,因此一次又一次使用 json.marshalindent 似乎是一项繁重的任务。

如何直接更改 bytes 变量?

代码位于 https://play.golang.org/p/8cmpwehmidr


解决方案


你别无选择,只能反复封送。使用 *json.Encoder 改善人体工程学和效率:

package main

import (
    "encoding/json"
    "log"
    "os"
)

type a struct {
    a int `json:"a"`
}

func main() {
    f, err := os.create("foo.json")
    if err != nil {
        log.fatal(err)
    }
    defer f.close()

    enc := json.newencoder(f)
    enc.setindent("", "\t")

    a := a{42} // using a pointer may improve performance if a is large.
    enc.encode(a)

    a.a = 666
    enc.encode(a)
}

buffered writer 包装文件也可以提高性能,具体取决于计算 as 的连续值的速度以及磁盘的速度。

您可以使用标准库来替换其中的字节给定的字节片。

https://golang.org/pkg/bytes/#Replace

package main

import (
    "bufio"
    "bytes"
    "encoding/json"
    "os"
)

type A struct {
    A int `json:"a"`
}

func main() {
    out := bufio.NewWriterSize(os.Stdout, 20)
    // defer out.Flush() // commented for demonstration purpose. Uncomment this to finalize the flush.
    a := A{42}
    b, _ := json.MarshalIndent(a, "", "\t")
    out.Write(b)
    b = bytes.Replace(b, []byte("42"), []byte("666"), -1)
    out.Write(b)
}

不建议这样做,但最终这是可能的。

我包含了一个缓冲编写器,用于演示其他答案和评论,不要忘记刷新它。

今天关于《修改 JSON 对象的二进制表示》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>