Skip to content

Instantly share code, notes, and snippets.

@nilesh-akhade
Created September 5, 2022 13:15
Show Gist options
  • Save nilesh-akhade/7a9b9dc3dc4b0f42264a3e5ab4f2be31 to your computer and use it in GitHub Desktop.
Save nilesh-akhade/7a9b9dc3dc4b0f42264a3e5ab4f2be31 to your computer and use it in GitHub Desktop.
Golang - Read JSON with leading white spaces or invalid characters
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"strings"
)
func main() {
r := getReader()
var b byte
var leadingStr strings.Builder
br := bufio.NewReaderSize(r, 2048)
for {
nextBytes, err := br.Peek(1)
checkErr(err)
if string(nextBytes) == "{" {
break
}
b, err = br.ReadByte()
checkErr(err)
err = leadingStr.WriteByte(b)
checkErr(err)
}
fmt.Println(leadingStr.String())
data, err := decodeJson(br)
checkErr(err)
fmt.Println(data)
}
func decodeJson(r io.Reader) (map[string]string, error) {
data := make(map[string]string)
err := json.NewDecoder(r).Decode(&data)
return data, err
}
func getReader() io.Reader {
return strings.NewReader(`Some gibberish before valid json
More gibberish
{"hello":"world"}`)
}
func checkErr(err error) {
if err != nil {
log.Fatalf("%v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment