【问题标题】:Changing the last character of a file更改文件的最后一个字符
【发布时间】:2019-02-25 13:23:32
【问题描述】:

我想不断地将 json 对象写入文件。为了能够阅读它,我需要将它们包装成一个数组。我不想阅读整个文件,以进行简单的附加。所以我现在在做什么:

comma := []byte(", ")
    file, err := os.OpenFile(erp.TransactionsPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
    if err != nil {
        return err
    }
    transaction, err := json.Marshal(t)
    if err != nil {
        return err
    }
    transaction = append(transaction, comma...)
    file.Write(transaction)

但是通过这个实现,我需要在阅读之前手动(或通过一些脚本)添加[]scopes。如何在每次写作关闭范围之前添加一个对象?

【问题讨论】:

  • “我需要在阅读之前手动添加[] 范围” - 为什么?你不能分别解析每一行并一个一个地填充你的数组吗?
  • @SergioTulentsev 我的意思是能够简单地将 Unmarshal 它放入一些 go 结构中
  • 它是一个数组,虽然(而不是结构)?
  • @SergioTulentsev 结构切片)
  • 啊,那为什么不逐行解组并填满你的切片呢?

标签: json file go file-writing


【解决方案1】:

您不需要将 JSON 对象包装到数组中,您可以按原样编写它们。您可以使用json.Encoder 将它们写入文件,也可以使用json.Decoder 读取它们。 Encoder.Encode()Decoder.Decode() 对流中的单个 JSON 值进行编码和解码。

为了证明它有效,请看这个简单的例子:

const src = `{"id":"1"}{"id":"2"}{"id":"3"}`
dec := json.NewDecoder(strings.NewReader(src))

for {
    var m map[string]interface{}
    if err := dec.Decode(&m); err != nil {
        if err == io.EOF {
            break
        }
        panic(err)
    }
    fmt.Println("Read:", m)
}

它输出(在Go Playground 上试试):

Read: map[id:1]
Read: map[id:2]
Read: map[id:3]

在写入/读取文件时,将os.File 传递给json.NewEncoder()json.NewDecoder()

这是一个完整的演示,它创建一个临时文件,使用 json.Encoder 将 JSON 对象写入其中,然后使用 json.Decoder 读回它们:

objs := []map[string]interface{}{
    map[string]interface{}{"id": "1"},
    map[string]interface{}{"id": "2"},
    map[string]interface{}{"id": "3"},
}

file, err := ioutil.TempFile("", "test.json")
if err != nil {
    panic(err)
}

// Writing to file:
enc := json.NewEncoder(file)
for _, obj := range objs {
    if err := enc.Encode(obj); err != nil {
        panic(err)
    }
}

// Debug: print file's content
fmt.Println("File content:")
if data, err := ioutil.ReadFile(file.Name()); err != nil {
    panic(err)
} else {
    fmt.Println(string(data))
}

// Reading from file:
if _, err := file.Seek(0, io.SeekStart); err != nil {
    panic(err)
}
dec := json.NewDecoder(file)
for {
    var obj map[string]interface{}
    if err := dec.Decode(&obj); err != nil {
        if err == io.EOF {
            break
        }
        panic(err)
    }
    fmt.Println("Read:", obj)
}

它输出(在Go Playground 上试试):

File content:
{"id":"1"}
{"id":"2"}
{"id":"3"}

Read: map[id:1]
Read: map[id:2]
Read: map[id:3]

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 2014-01-24
    • 2012-07-06
    • 1970-01-01
    • 2012-01-11
    • 2013-09-22
    • 2015-10-27
    • 2021-11-06
    相关资源
    最近更新 更多