Skip to content

Commit

Permalink
feat: handle invalid JSON lines
Browse files Browse the repository at this point in the history
  • Loading branch information
oprogramador committed Sep 6, 2021
1 parent 80e1270 commit 8a84e18
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 2 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,8 @@ expect(result).to.deep.equal([
{ foo2: 'bar2' },
]);
```

## specification
* It omits every line which isn't a valid JSON.
* For the remaining lines, it converts every line into an object.
* So it always returns an array (possibly an empty array if there's no line with a valid JSON).
11 changes: 9 additions & 2 deletions src/readJsonLines.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
function readJsonLines(string) {
return string.split('\n')
.filter(line => line)
.map(line => line.trim())
.filter((line) => {
try {
JSON.parse(line);

return true;
} catch (error) {
return false;
}
})
.map(line => JSON.parse(line));
}

Expand Down
65 changes: 65 additions & 0 deletions src/tests/readJsonLines.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,69 @@ describe('readJsonLines', () => {
{ foo3: 'bar3', lorem: [1, 2, 3] },
]);
});

it('returns empty array for one invalid JSON line', () => {
const lines = 'foo';

const result = readJsonLines(lines);

expect(result).to.deep.equal([]);
});

it('returns empty array for two invalid JSON lines', () => {
const lines = `foo
bar`;

const result = readJsonLines(lines);

expect(result).to.deep.equal([]);
});

it('returns a one-element array for a one-line string followed by one invalid JSON line', () => {
const lines = `{"foo":"bar"}
baz`;

const result = readJsonLines(lines);

expect(result).to.deep.equal([
{ foo: 'bar' },
]);
});

it('returns a one-element array for a one-line string preceded by one invalid JSON line', () => {
const lines = `baz
{"foo":"bar"}`;

const result = readJsonLines(lines);

expect(result).to.deep.equal([
{ foo: 'bar' },
]);
});

it('returns a one-element array for a one-line string preceded and followed by one invalid JSON line', () => {
const lines = `baz
{"foo":"bar"}
baz2`;

const result = readJsonLines(lines);

expect(result).to.deep.equal([
{ foo: 'bar' },
]);
});

it('returns a two-element array for a two-line string having an invalid JSON line between', () => {
const lines = `{"foo":"bar"}
baz
{"foo2":"bar2"}
`;

const result = readJsonLines(lines);

expect(result).to.deep.equal([
{ foo: 'bar' },
{ foo2: 'bar2' },
]);
});
});

0 comments on commit 8a84e18

Please sign in to comment.