英文:
"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.ReadFile
和json.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论