File tree Expand file tree Collapse file tree 2 files changed +23
-2
lines changed Expand file tree Collapse file tree 2 files changed +23
-2
lines changed Original file line number Diff line number Diff line change @@ -114,9 +114,19 @@ export function toUnixNewlines(text: string): string {
114114 return platform ( ) === 'win32' ? text . replace ( / \r \n / g, '\n' ) : text ;
115115}
116116
117- export function fromJsonLines < T = unknown > ( jsonLines : string ) {
117+ export function fromJsonLines < T extends unknown [ ] > ( jsonLines : string ) {
118118 const unifiedNewLines = toUnixNewlines ( jsonLines ) . trim ( ) ;
119- return JSON . parse ( `[${ unifiedNewLines . split ( '\n' ) . join ( ',' ) } ]` ) as T ;
119+ const invalid = Symbol ( 'invalid json' ) ;
120+ return unifiedNewLines
121+ . split ( '\n' )
122+ . map ( line => {
123+ try {
124+ return JSON . parse ( line ) ;
125+ } catch {
126+ return invalid ;
127+ }
128+ } )
129+ . filter ( line => line !== invalid ) as T ;
120130}
121131
122132export function toJsonLines < T > ( json : T [ ] ) {
Original file line number Diff line number Diff line change @@ -258,6 +258,17 @@ describe('JSON lines format', () => {
258258
259259 expect ( fromJsonLines ( jsonLines ) ) . toEqual ( [ head , body ] ) ;
260260 } ) ;
261+
262+ it ( 'should ignore non-JSON lines' , ( ) => {
263+ const jsonLines = [
264+ '(node:346640) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.' ,
265+ '(Use `node --trace-deprecation ...` to show where the warning was created)' ,
266+ JSON . stringify ( head ) ,
267+ JSON . stringify ( body ) ,
268+ ] . join ( '\n' ) ;
269+
270+ expect ( fromJsonLines ( jsonLines ) ) . toEqual ( [ head , body ] ) ;
271+ } ) ;
261272 } ) ;
262273
263274 describe ( 'toJsonLines' , ( ) => {
You can’t perform that action at this time.
0 commit comments