jsonlines.go 720 B

1234567891011121314151617181920212223242526
  1. package reader
  2. import (
  3. "encoding/json"
  4. "io"
  5. )
  6. // NewJSONLinesReader returns a Reader[T] that streams a sequence of JSON values
  7. // read from an underlying io.Reader. It handles JSON Lines (one JSON value per
  8. // line), which can be whitespace/newline-separated (or not) and consolidated
  9. // to a single line each (or not, e.g. pretty-printed). Stops on io.EOF from
  10. // the underlying reader. If the underlying reader is also an io.Closer, it
  11. // will close it on Close().
  12. func NewJSONLinesReader[T any](r io.Reader) *FuncReader[T] {
  13. dec := json.NewDecoder(r)
  14. next := func() (T, error) {
  15. var item T
  16. err := dec.Decode(&item)
  17. return item, err
  18. }
  19. closer, _ := r.(io.Closer)
  20. return NewFuncReader(next, closer)
  21. }