Skip to content

Commit edde373

Browse files
authored
fix: invalid JSON output when --json flag used (#2666)
1 parent 6936d4d commit edde373

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

cli/src/json-check-schema-output-builder.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -199,13 +199,23 @@ export class JsonCheckSchemaOutputBuilder {
199199
return this.data;
200200
}
201201

202+
/**
203+
* Writes valid JSON either to stdout or a file.
204+
*/
202205
async write(): Promise<void> {
203-
const output = this.build();
204-
205206
if (this.outFile) {
206-
await writeFile(this.outFile, JSON.stringify(output, null, 2));
207+
await writeFile(this.outFile, this.serializeOutput(true));
207208
} else {
208-
console.log(output);
209+
console.log(this.serializeOutput());
210+
}
211+
}
212+
213+
private serializeOutput(formatted = false): string {
214+
try {
215+
return JSON.stringify(this.build(), null, formatted ? 2 : 0);
216+
} catch (err) {
217+
console.error('Failed to serialize JSON data.');
218+
throw err;
209219
}
210220
}
211221
}

cli/test/json-check-schema-output-builder.test.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,19 @@ describe('JsonCheckSchemaOutputBuilder', () => {
297297
const b = new JsonCheckSchemaOutputBuilder(EnumStatusCode.OK, 10);
298298
b.setStatus(true);
299299
await b.write();
300-
expect(spy).toHaveBeenCalledWith(b.build());
300+
expect(spy).toHaveBeenCalledWith('{"status":"success","code":0,"rowLimit":10}');
301+
});
302+
303+
it('serializes LintIssue instances to plain objects in JSON output', async () => {
304+
const spy = vi.spyOn(console, 'log').mockImplementation(() => {});
305+
const b = new JsonCheckSchemaOutputBuilder(EnumStatusCode.OK, 10);
306+
b.addLintErrors([new LintIssue({ message: 'lint error', lintRuleType: 'RULE_A' })]);
307+
b.addLintWarnings([new LintIssue({ message: 'lint warn', lintRuleType: 'RULE_B' })]);
308+
await b.write();
309+
310+
expect(spy).toHaveBeenCalledWith(
311+
'{"status":"error","code":0,"rowLimit":10,"lint":{"errors":[{"lintRuleType":"RULE_A","severity":"warn","message":"lint error"}],"warnings":[{"lintRuleType":"RULE_B","severity":"warn","message":"lint warn"}]}}',
312+
);
301313
});
302314

303315
it('writes JSON to file when outFile provided', async () => {

0 commit comments

Comments
 (0)