Skip to content

Instantly share code, notes, and snippets.

@polynomialspace
Last active March 24, 2021 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polynomialspace/6d7a27fffa140883d1f3cfea91b905a8 to your computer and use it in GitHub Desktop.
Save polynomialspace/6d7a27fffa140883d1f3cfea91b905a8 to your computer and use it in GitHub Desktop.
ndjson -> json array (technically golang will take '\n' as a json sep where ndjson is '\r\n' but /shrug)
// NDjsonTojsonArr converts newline-delimited json (indented or minified)
// to a json array. Caller should handle cleanup on error.
func NDjsonTojsonArr(r io.Reader, w io.WriteCloser) error {
w.Write([]byte("["))
var m json.RawMessage
dec := json.NewDecoder(r)
err := dec.Decode(&m)
for {
if _, err = w.Write(m); err != nil {
return err
}
if err = dec.Decode(&m); err != nil {
if err != io.EOF {
return err
}
break
}
if _, err = w.Write([]byte(",")); err != nil {
return err
}
}
_, err = w.Write([]byte("]"))
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment