Pankaj
Pankaj

Reputation: 3712

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

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 ?

Upvotes: 7

Views: 9356

Answers (2)

jimt
jimt

Reputation: 26447

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.

Upvotes: 5

cthom06
cthom06

Reputation: 9655

When you write the data to disk, are you making sure to pass os.O_TRUNC (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.

Upvotes: 3

Related Questions