duanke1984 2014-08-18 21:44
浏览 247
已采纳

Golang:转换为JSON.GZ并写入文件

Trying to accomplish the following output with my data:

  1. Convert to JSON string and write to file: output.json (this part is working)
  2. Gzip Compress the JSON string and write that to a json.gz file: output.json.gz (NOT WORKING)

The code runs fine and writes to both files. But the gzipped file gives this error when I try to unzip it: Data error in 'output.json'. File is broken

Here's the code:

package main

import (
    "bytes"
    "compress/gzip"
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type Generic struct {
    Name string
    Cool bool
    Rank int
}

func main() {
    generic := Generic{"Golang", true, 100}
    fileJson, _ := json.Marshal(generic)
    err := ioutil.WriteFile("output.json", fileJson, 0644)
    if err != nil {
        fmt.Printf("WriteFileJson ERROR: %+v", err)
    }

    var fileGZ bytes.Buffer
    zipper := gzip.NewWriter(&fileGZ)
    defer zipper.Close()
    _, err = zipper.Write([]byte(string(fileJson)))
    if err != nil {
        fmt.Printf("zipper.Write ERROR: %+v", err)
    }
    err = ioutil.WriteFile("output.json.gz", []byte(fileGZ.String()), 0644)
    if err != nil {
        fmt.Printf("WriteFileGZ ERROR: %+v", err)
    }
}

What did I miss?

  • 写回答

2条回答

  • duanquyong8164 2014-08-18 21:55
    关注

    You need to call zipper.Close() immediately after finishing writing

    http://play.golang.org/p/xNeMg3aXxO

    _, err = zipper.Write(fileJson)
    if err != nil {
        log.Fatalf("zipper.Write ERROR: %+v", err)
    }
    err := zipper.Close() // call it explicitly and check error 
    

    Calling defer zipper.Close() would trigger the call at the end of the main function. Until you call .Close() the data is being written to an intermediate buffer and not flushed to the actual file.

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

报告相同问题?

悬赏问题

  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置