dt250827 2018-08-31 10:24
浏览 15
已采纳

更改以JSON对象的字节表示形式归档

I write A object to a file f.

a := A{42}
bytes, _ := json.MarshalIndent(a, "", "\t")
f.Write(bytes)

Where A looks like:

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

Then I change field of this object and write it to the file:

a.A = 666
f.Write(bytes)

As a result, I see only

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

While I expected:

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

I know that I can overcome it by using json.MarshalIndent again. But I need to do a lot of (~10^6) writings to the file, so using json.MarshalIndent again and again seems to be a heavy task.

How can I directly change a bytes variable?

Code is located at https://play.golang.org/p/8CMpwehMidR

  • 写回答

2条回答 默认 最新

  • dongzhang1987 2018-08-31 10:53
    关注

    You have no choice but to marshal repeatedly. Use a *json.Encoder for improved ergonomics and efficiency:

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

    Wrapping the file with a buffered writer may also improve performance, depending on how quickly you can compute successive values for the As and how fast the disk is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置