“解析JSON时,在顶层值之后出现无效字符 ‘1’”

huangapple go评论87阅读模式
英文:

"invalid character '1' after top-level value " unmarshaling JSON

问题

我在程序调用之间使用json来存储数据在磁盘上,程序运行一段时间后,出现了json解码错误,错误信息为"invalid character '1' after top-level value"。

有人能提供一些解决这个问题的方法吗?

英文:

I am using json to store data on disk between program calls, the program runs fine for some time, but after that it displays error in json decoding, "invalid character '1' after top-level value ".

Can anyone suggest some solution to this problem ?

答案1

得分: 5

不要手动打开文件,考虑使用一些内置的IO函数。

import (
  "io/ioutil"
  "encoding/json"
)
...
func Save(myobj SomeType, filename string) (err error) {
    var data []byte
    if data, err = json.Marshal(myobj); err != nil {
        return
    }
    return ioutil.WriteFile(filename, data)
}

在加载json数据时,同样可以使用ioutil.ReadFilejson.Unmarshal

英文:

Instead of doing the manual file opening, consider using some of the inbuilt IO functions.

import (
  "io/ioutil"
  "encoding/json"
)
...
func Save(myobj SomeType, filename string) (err error) {
    var data []byte
    if data, err = json.Marshal(myobj); err != nil {
        return
    }
    return ioutil.WriteFile(filename, data)
}

The same goes for loading of json data where you use ioutil.ReadFile and json.Unmarshal.

答案2

得分: 3

当你将数据写入磁盘时,你是否确保在打开标志中传递<code>os.O_TRUNC</code>(或以其他方式截断文件)?如果没有,程序将正常工作,直到你写入一个比最后一个对象更小的对象。但是,如果看不到代码,很难调试。

英文:

When you write the data to disk, are you making sure to pass <code>os.O_TRUNC</code> (or otherwise truncate the file) in the open flags? If not, the program will work fine until you write an object smaller than the last. But it's hard to debug code without seeing it.

huangapple
  • 本文由 发表于 2010年7月3日 17:47:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/3171075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定